第一个for循环它给了我正确的答案,最低为0.00 然而,当我添加第二个for循环以跟踪具有0.00降雨量的月数时,第一个for循环表示“nan”,而第二个for循环表示正确答案为2。
#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 :(得分:3)
初始化lowest
:
float lowest=100.00; //or any other term, like INT_MAX
如果没有初始化,您就不会知道lowest
可能包含的值,因此在进一步的计算中会给出错误的值。