【问题标题】:Double variable outputs 32767 always instead of user input双变量输出 32767 始终而不是用户输入
【发布时间】:2019-10-18 04:44:40
【问题描述】:

我正在编写代码,询问每个月的降雨量,然后输出年总降雨量、月平均降雨量、最小和最大降雨月份(索引)。我的代码几乎是完整的,除了输出总是显示变量类型 32767 的最大范围(例如,如果雨是 70 毫米和最大值,控制台总是显示 32767),而不是输出最大值。谢谢你的帮助。我在自学。

我已经尝试了以下代码。

#include<iostream>
using namespace std;

int main(){
    const int numMonths = 3;
    double monthlyRain[numMonths]={0,0,0};
    string monthName[numMonths]= {"Jan", "Feb", "Mar"};
    int count = 0;
    int indexWettest = 0;
    int indexDriest = 0;
    double  yearTotal=0, monthlyAverage=0;
    double monthHighest;
    double monthLowest;

    monthLowest = monthlyRain[0];
    monthHighest = monthlyRain[0];


    // enter monthly rain;
    for (int count=0; count < numMonths; count++){
        cout << "Please enter amount of rain in " << monthName[count] << endl;
        cin >> monthlyRain[count];
    }


    // print month and corresponding rain amount;
    cout << "Month --- Rain(mm)" << endl;
    for (int count = 0; count < numMonths; count++){
        cout << monthName[count] << " " << monthlyRain[count] << endl;
    }


    // calculate year total;
    for (int count = 0; count < numMonths; count++){
        yearTotal += monthlyRain[count];
    }

    // calculate average monthly rainfall;
    monthlyAverage = yearTotal/numMonths;

    // find month with lowest rainfall;


    // find month with highest rainfall;

    for (int count = 0; count < numMonths; count++){    
        if (monthlyRain[count] > monthHighest){
            monthHighest = monthlyRain[count+1];
            indexWettest = count;
        }
    }


// PROBLEM IS HERE!;
    for (int count = 0; count < numMonths; count++){
        if (monthlyRain[count] < monthLowest){
            monthLowest = monthlyRain[count];
            indexDriest = count;

        }

    }

    cout << "Total yearly rain fall is: " << yearTotal << endl;
    cout << "Average monthly rainfall is: " << monthlyAverage << endl;
    cout << "The driest month is " <<  monthName[indexDriest] << " with rain amount of  " << monthLowest << endl;
    cout << "The wettest month is " <<  monthName[indexWettest] << " with rain amount of  " << monthHighest << endl; //<< monthName[indexWettest];

return 0;
}

预期结果是用户输入。

【问题讨论】:

  • 您可能想要启用一些编译器警告,请参阅compiler explorer,这可能表明您的代码中有几个错误
  • 您正在使用monthlyRain[0] 初始化monthLowestmonthHighest,它本身并未初始化,因此您的程序的其余部分会产生未定义的行为。
  • @goodvibration Nitpick:未定义的行为不限于“程序的其余部分”。由于不可避免地会得出有问题的赋值,因此整个程序具有未定义的行为。
  • 感谢您的反馈。我为变量和数组添加了初始值(参见修改后的代码)。但问题仍然存在。问题只出现在最后一个循环代码中。

标签: c++ variables types output double


【解决方案1】:

阅读编译器警告。

main.cpp:35:19: warning: 'yearTotal' may be used uninitialized in this function [- 
Wmaybe-uninitialized]

yearTotal += monthlyRain[count];

声明 yearTotal 的行应该是 double yearTotal = 0;

与其他变量相同。始终初始化它们。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-06-02
  • 2017-02-04
  • 1970-01-01
  • 2014-06-04
  • 2013-06-22
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多