如何找到數組中的最小值?我認爲我做得很對,但是當我運行這個程序時它輸出爲零。如何輸出輸入到數組中的最小值? (C++)
我在另一個程序中做了同樣的工作,它工作。運行時,顯示最高的元素,但最低的顯示爲零。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE = 12;
double rainfall[ARRAY_SIZE];
double total_year, monthly_average;
double highest = rainfall[0];
double lowest = rainfall[0];
cout << " Input rainfall for each month: \n" ;
for(int index = 0; index < ARRAY_SIZE; index++)
{
cout << " Month " << index+1 << ": " ;
cin >> rainfall[index];
total_year += rainfall[index];
if(rainfall[index] < 0)
{
cout << " Rainfall must equal to 0 or higher: " ;
cin >> rainfall[index];
}
}
for(int x = 0; x < ARRAY_SIZE; x++)
{
if(highest < rainfall[x])
{
highest = rainfall[x];
}
if(lowest > rainfall[x])
{
lowest = rainfall[x];
}
}
cout << fixed << setprecision(2) << endl;
cout << " There was " << total_year << " inches" ;
cout << " of rainfall this year. \n" ;
cout << " The monthtly average was " << total_year/12 ;
cout << " inches of rainfall.\n";
cout << " The highest rainfall was " << highest << " inches" << endl;
cout << " The lowest rainfall was " << lowest << " inches" << endl;
return 0;
}
使用您的調試器。 – Charles
@Seyfat Khamidov聲明這些變量時,數組未被初始化。雙倍最高=降雨量[0]; 雙下最低=降雨[0];所以變量有不確定的值。你必須在數組填充後初始化變量。 –
如果您的total_year變量嘗試以降雨量[指數]增加並且其值低於0,那麼您的total_year變量將不準確。然後,您要求用戶輸入相同指數下降的新值。 –