我刚刚开始编程,正在尝试编写与我不太同意的代码。

我的主要问题是:


激活捕获后,我希望该程序再次运行,以便可以输入新的数字,但现在只是关闭它。
我希望先将FahrenheitToCelsius转换为float,然后再将其作为int插入。


我在这里遇到的类似问题中尝试了许多不同的选择,但由于我的代码似乎都无法正常工作,所以现在我已经处于停滞状态(可能是因为我还没有看到全部图片)。

到目前为止,这是我的代码,其中没有所有失败的尝试,以使其易于忽略。

class Program
{

    //METHOD: CONVERTS FAHRENHEIT TO CELSIUS
    public static int FahrenheitToCelsius (int fahrenheit)
    {
        int celsius = ((fahrenheit - 32) * 5) / 9;
        return celsius;
    }


    public static void Main(string[] args)
    {
        try
        {
            //===============INTRO AND METHOD CALLING============
            Console.WriteLine("Skriv in temperaturen i Fahrenheit: ");
            int fahrenheit = int.Parse(Console.ReadLine());
            int cel = FahrenheitToCelsius(fahrenheit);



            //==============-NOT ACCEPTABLE TEMPERATURES==============
            do

                //ABOVE ACCEPTABLE TEMP
                if (cel > 77)
                {
                    Console.WriteLine("This is too hot. Turn down the temperature.");
                    int cel3 = int.Parse(Console.ReadLine());
                    cel = FahrenheitToCelsius(cel3);


                }

                //BELOW ACCEPTABLE TEMPERATURE
                else if (cel < 73)
                {
                    Console.WriteLine("This is too cold. Turn up the temperature");
                    int cel2 = int.Parse(Console.ReadLine());
                    cel = FahrenheitToCelsius(cel2);
                }


            while (cel < 73 || cel > 77);



            //================ACCEPTABLE TEMPS===================

            //Acceptable but not perfect temp
            if (cel == 73 || cel == 74 || cel == 76 || cel == 77)
            {
                Console.WriteLine("Acceptable temperature.");
            }

            //PERFECT TEMPERATURE
            else if (cel == 75)
            {
                Console.WriteLine("Perfect temperature!");
            }
        }

        //================EXCEPTION=================
        catch (Exception)
        {
            Console.WriteLine("Error. Only numbers acceptable.");

        }

            Console.ReadKey();
    }
}


}

正如我所说,我是编程的超级新手,所以答案可能就在我眼前,但是仅在尝试了这两个问题的12个小时之后,我想我需要一些帮助!

最佳答案

如果要浮点数而不是整数,则可以使用float.Parse()代替int.Parse

如果要继续使用无效输入进行处理,可以使用TryParse代替Parse,如下所示:

float fahrenheit = 0;
float cel;
while (fahrenheit == 0)
{
    if (float.TryParse(Console.ReadLine(), out farhenheit)
        cel = fahrenheit;
    else
        Console.WriteLine("Error. Only numbers acceptable.");
}

10-07 19:10
查看更多