You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:天气模拟器中无法使用随机数赋值变量的问题

Fixing Your Weather Simulator's Random Wind Speed Issue

Let's break down what's going wrong here and fix it step by step:

1. Your Random Number Only Generates Once

The biggest issue is that randwmph = random.randint(1, 99) is defined outside your while True loop. That means this random number is generated once when the program starts, and stays the same through every loop iteration—so you're not getting a new random value each time you need to adjust the wind speed.

2. Redundant Module Imports

You're importing the random module twice:

import random
from random import*

This is unnecessary and can cause confusion. Stick to one import style (I'd recommend import random for clarity, so you explicitly reference random.randint()).

3. Potential Wind Speed Underflow

When wmph >=60, subtracting randwmph could make wmph negative, which might break your intended weather logic. We can add a check to keep it at a minimum of 0 (or adjust to your desired floor).

Corrected Code

import random

t = 100
wmph = 51
h = 25

print ("\nDynamic Weather Simulator | V.004\n")
while True:
    if t >= 0 and t <= 150:
        print("\nHumidity:",h)
        print("\nTemperature:",t)
        print("\nWindSpeed:",wmph)
        print("\n________________\n")
        if t >= 5 and t <= 100:
            h = h + 0.6
            if h >= 50 and t >= 33:
                print("\nRAINFALL\n")
            if h >= 50 and t <= 32:
                print("\nSNOWFALL\n")
            if h >= 55:
                h = h - 20
        if wmph >= 30:
            t = t - 2
        if wmph <= 29:
            t = t + 1
        if wmph >= 60:
            # Generate a NEW random number each time we need to adjust wind speed
            randwmph = random.randint(1, 99)
            # Ensure wind speed doesn't drop below 0
            wmph = max(0, wmph - randwmph)
        else:
            wmph = wmph + 4

Key Changes Explained:

  • Moved randwmph = random.randint(1, 99) inside the wmph >=60 condition block, so it generates a fresh random number every time wind speed needs to be reduced.
  • Removed the redundant from random import* import to keep the code clean.
  • Added max(0, wmph - randwmph) to prevent wind speed from becoming negative (tweak the 0 if you want a different minimum wind speed value).

Now your random wind speed adjustment should work as expected—each time wind speed hits 60+, it'll subtract a new random value between 1 and 99.

内容的提问来源于stack exchange,提问作者taylorbeeler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:08:04