2017-09-05 66 views
-7

我被赋予一项任务来制作一个程序,该程序允许用户将12个月的每个月的总降雨量输入到一个双精度数组中。C++循环在第一次迭代时被卡住

程序应该计算并显示年份的总降雨量,月平均降雨量以及最高和最低量的月份。

我的教授要求我简单地修改她为我们提供的骨架。程序编译得很好,问题是在第一次迭代中它显示了第一个月,但是停在那里。

不知道我在做什么错,有什么想法?

以下是有关区域的代码。

void getMonthlyRainfalls(double rainfallsArr[], int size, int month){ 
cout << "Please type the rainfalls occurring in the month " << (month+1) << ": " ; 

do{ 
    if (! cin){ 
    cin.clear(); 
    cin.ignore(1124, '\n'); 
    } 

    for (int i = 0; i < size; i++) 
     cin >> rainfallsArr[month]; 

    if (!cin || rainfallsArr[month] < 0) 
     cout << "Please retype the rainfalls occurring in the month " << (month+1) << ": " ; 
    } while (!cin || rainfallsArr[month] < 0); 
} 
+0

为什么你循环大小的时间来获得一个月的降雨量,并将其重复存储在覆盖前一个相同的位置?如果它不是12,我很困惑什么大小代表。也许你应该在循环中加入值,如果每月有多个降雨总数的话。 – drescherjm

+0

这是有点问题,我似乎无法弄清楚如何解决它我知道问题是与循环,但我不能看到我出错的地方 –

+0

我会摆脱两个循环,但我仍然不知道什么大小是。 – drescherjm

回答

1

这是你的任务的解决方案

#include <iostream> 
using namespace std; 
int main() 
{ 
double rain_fall[12] , maxi=0 , mini , sum=0; // maxi for the highest 
//amount mini for the lowest 
for(int i=0; i<12; i++) 
{ 
    cout<<"please enter the total amount of rainfall in the month number " 
    <<i+1<< endl; 
    cin>>rain_fall[i]; 
    if(i==0) 
     mini=rain_fall[i]; // happened just once to give it an initial 
    value from the array 
    if(maxi<rain_fall[i]) // the highest amount 
     maxi=rain_fall[i]; 
    else if (mini>rain_fall[i]) 
     mini=rain_fall[i]; // the lowest amount 
    sum+=rain_fall[i]; 
} 
cout<<"the total amount in the year is : "<<sum<< endl; 
cout<<"the average amount per month is : "<<sum/12<< endl; 
cout<<"the highest amount in the year is : "<<maxi<< endl; 
cout<<"the lowest amount in the year is : "<<mini<< endl; 
return 0; 
} 

什么,我在这里做
我做了一个快捷方式通过compering,以获得最高和最低值时 采取从用户输入和这里是代码的解释..

首先我从用户的输入,然后为第一个输入,只是一次我给微型值cuz它必须给我一个值从我输入数组cuz如果我们为它指定一个零,并且所有的月份数量都大于零,但EX的最低数量是2,这将成为一个错误,因为if语句会给我最低的金额,如果0> [什么值] 每次它将是错误的,所以最小值将保持其中的零并显示为最低值,但实际上我们没有数组中的零,最低值为2,因为我们假设因此,mini应该有一个存在于数组中的值,它包含数量为

之后,我们对它做一个if语句以与输入进行比较以保存其中的最大值,并且我们分配了一个零,因为任何东西都会大于零,所以如果(0 < [无论什么价值])将进展顺利,然后假如我们已经获得最大价值

后,我们在和可变的输入加在一起后,在COUT语句获取的所有月份总量

获得每月平均量U除以每12个总[月的数量]

+4

这个答案是缺乏解释。 –

+0

我上面写过。 –

-1

while(cin & & rainfallsArr [month]> 0);

+2

你能为你的答案提供更多的上下文吗? – alexi2