浮点变量在开关状态内不起作用

Float Variable Not Working Inside Switch Statment

本文关键字:不起作用 状态 开关 浮点变量      更新时间:2023-10-16

所以这个程序应该使用for循环收集7天的天气温度,然后基本上只是将它们打印回用户,平均温度和最高记录温度。请记住,以下代码段是一个更大的程序的一部分。无论如何,问题似乎是"highest_temp1"浮点变量。当我运行程序时,它会产生某种错误代码,而不是最高温度。这段代码在单独的源文件中进行了测试,它没有问题。

switch (choice)
    {
    case 3:
        int n;
        float temperatures [7];
        float lastweektemp [7] = {12.56,8.65,7.5,10,7.9,5,8};
        float highest_temp1, highest_temp2;
        float accumulated_temp1, accumulated_temp2;
        system("CLS");
        cout << "____________Weather Data____________" << endl << endl;
        for (n = 0; n<7; n++)
        {
            cout << "What is the temperature for Day " << n+1 << " ?" << endl;
            cin >> temperatures[n];
            if (highest_temp1 < temperatures [n])
            {
                highest_temp1 = temperatures [n];
            }
            if (highest_temp2 < lastweektemp [n])
            {
                highest_temp2 = lastweektemp [n];
            }
           accumulated_temp1 = accumulated_temp1 + temperatures[n];
           accumulated_temp2 = accumulated_temp2 + lastweektemp [n];
        }
        cout << endl << " Day    This Week    Last Week" << endl;
        for (n=0; n<7; n++)
        {
            cout << n+1 << temperatures[n] << lastweektemp[n] << endl;
        }
        system("CLS");
        cout << "              Weather Report" << endl;
        cout << "              --------------" << endl << endl;
        cout << "Current Week: " << endl;
        cout << "-------------" << endl;
        for (n=0; n<7; n++)
        {
            cout << "Day " << n+1 << ": " << temperatures[n] << endl;
        }
        cout << endl << "          Average: " << accumulated_temp1 / 7 << endl;
        cout << "          Highest Temperature: " << highest_temp1 << endl;
        cout << "Last Week: " << endl;
        cout << "----------" << endl;
        for (n=0; n<7; n++)
        {
            cout << "Day " << n+1 << ": " << lastweektemp[n] << endl;
        }
        cout << endl << "          Average: " << accumulated_temp2 / 7 << endl;
        cout << "          Highest Temperature: " << highest_temp2 << endl;
        system("PAUSE");

    }

本周的最高温度是24,但它正在打印"最高温度:3.45857e+032"
每次我运行程序时都会出现这个确切的"错误代码",它不会改变。

我是新手,因此为什么我不能上传照片。

任何帮助将不胜感激。我在大学里做一个小作业。这是我的第一个问题,所以放轻松!!

您尚未为变量highest_temp1赋值,并且正在将其与另一个值进行比较。

基本上,在比较之前,您需要先为其分配一个值。

highest_temp1 = 10.00

(或它应该包含的任何内容)

你还没有初始化highest_temp1(或者highest_temp1:在那之后我就停止了寻找)。

accumulated_temp相同,未初始化。 可以通过

float accumulated_temp1(0);

使用变量前初始化变量

float highest_temp1(-FLT_MAX);  // -FLT_MAX insures results of first compare
float highest_temp2(-FLT_MAX);  // Could use -1.0/0.0 of -INFINITY instead
float accumulated_temp1(0.0);
float accumulated_temp2(0.0);

对于浮点数条件,如果语句 switch 在浮点数的情况下无法工作,则 switch 仅适用于整数。