2015-05-05 61 views
-2

循环的第一个给了我正确的答案,它是最低的0.00。
然而,当我添加第二个for循环跟踪月份数为0.00降雨,第一for循环说“南”,而第二个for循环给出正确的答案是2无法获得for循环工作

#include <iostream> 
using namespace std; 
int main(){ 
    const int NUM = 12; 
    string month[NUM] = {"JAN","FEB","MAR","APR","MAY","JUNE","JULY","AUG","SEPT","OCT","NOV","DEC"}; 
    int counter = 0; 
    float lowest; 
    float rainfall [NUM] = {20.75, 34.60, 0.00, 4.12, 1.00, 72.99, 3.76, 10.00,  8.09, 64.05, 0.00, 30.02}; 
    for (int i = 0; i < NUM; i++) { 
     if ((rainfall[i] < rainfall [i-1]) && (rainfall[i] < lowest)) 
      lowest = rainfall[i]; 
    } 
    cout << lowest << endl; 
    for (int i = 0; i < NUM; i++) 
    { 
     if (rainfall[i] == 0.00) 
     counter += 1; 
    } 
    cout << counter; 
    return 0; 
} 
+0

对不起,在这里打字错误;请看我的代码,第一个for循环给我正确的答案,它是最低的0.00(当我独自运行时)。然而,当我添加第二个循环跟踪月降雨量为0.00的月份时,第一个for循环表示“nan”,而第二个for循环给出正确的答案,这是2.我做错了什么? –

回答

3

初始化lowest

float lowest=100.00; //or any other term, like INT_MAX 

没有初始化,你不知道会持什么样的价值lowest,因此将在进一步计算给出错误的价值观。

+0

哦!谢谢业力,初始化最低后,它工作得很好。 –