【问题标题】:I want to change/add a parameter in a loop and keep the loop running until the corrent temperature is entered [duplicate]我想在循环中更改/添加一个参数并保持循环运行直到输入正确的温度[重复]
【发布时间】:2026-02-18 10:20:04
【问题描述】:

我正在做一个项目,您可以在其中输入桑拿的温度,如果您输入低温,它会告诉您提高温度,直到温度足够高,但我需要它不断要求更高的温度,直到您获得足够高的温度而无需重新启动程序,因此我需要能够更改循环中的温度,然后写出循环外的温度。

static void Main(string[] args)
{
    Console.WriteLine("Enter temperature");
    String tempInput = Console.ReadLine();
    Int32 tempF = Convert.ToInt32(tempInput);
    Int32 tempC = (tempF - 32) * 5 / 9;
    Int32 tempCInDoLoop = 0;

    Console.WriteLine("Temperature is to low, enter a higher temperature");

    if (tempC < 73 && tempCInDoLoop < 73)
    {
        Console.WriteLine("Enter higher temperature");
        String tempInputInDoLoop = Console.ReadLine();
        Int32 tempFInDoLoop = Convert.ToInt32(tempInputInDoLoop);
        Int32 tempCInDoLoop = (tempFInDoLoop - 32) * 5 / 9;
    }
    //Console.WriteLine(tempFInDoLoop);
}

【问题讨论】:

标签: c#


【解决方案1】:

我想给你一些你可以学习的东西:

static void Main(string[] args)
{
    Console.WriteLine("Enter temperature");
    
    double temperatureC = double.NaN;

    while (double.TryParse(Console.ReadLine(), out temperatureC) && temperatureC < 73.0)
    {
        Console.WriteLine($"{temperatureC}°C is to low, enter a higher temperature");
    }
    
    double temperatureF = temperatureC * 9.0 / 5.0 + 32.0;

    Console.WriteLine($"{temperatureC}°C, {temperatureF}°F");
}

看看这是否满足你的需要。

【讨论】:

  • 这有点用,但我现在也需要添加最高温度,我尝试复制代码并更改操作数,但我收到错误代码 CS0128“函数的局部变量nemed 'temperatureC' 已在此范围内定义”。你知道如何解决这个问题吗?当第二个循环处于活动状态时,第二个 while 循环也不会写出 WriteLine
  • 你应该只声明一次变量。如果你有一个最小和一个最大温度,那么你有两个变量,你应该声明一次。
  • 我也不明白您所说的“当第二个循环处于活动状态时,第二个 while 循环不会写出 WriteLine”是什么意思。您可能需要向我提供您编写的代码。
最近更新 更多