-2
我用Dev C++ 5.5.3來編寫一些程序。其中一個程序是關於獲取一些數字(整數),直到零,然後打印最大值,最小值,平均值。在我的電腦裏,一切都很好。在別人的電腦中,它並沒有顯示出正確的平均值,它顯示了非常奇怪的數字4.612521 e + 8並且像這樣。我定義了一個變量avg並計算出這個值然後打印出來。另一個在調用cout時直接計算平均值。有人可以檢查此程序: 計劃1不顯示正確答案:使用cout和平均值的錯誤或錯誤
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n;
int max , min , count = 0 , s;
float avg;
cout<<"This program gets some numbers until zero and then prints maximum, minimum and average of them"<<endl<<"Please enter a number : ";
cin>> n;
max = n;
min = n;
while (n!= 0)
{
count ++;
s+=n;
if (n>max)
{
max = n;
}
if (n<min)
{
min = n;
}
cout<< "Please enter a number : ";
cin>>n;
}
cout<<"ZERO DETECTED!\n\n"<<endl;
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
avg = (float) s/count ;
cout<<"Average: "<<avg<<endl; // NOTE NOTE NOTE NOTE
return 0;
}
方案2中顯示了正確的答案:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n;
int max , min , count = 0 , s;
float avg;
cout<<"This program gets some numbers until zero and then prints maximum, minimum and average of them"<<endl<<"Please enter a number : ";
cin>> n;
max = n;
min = n;
while (n!= 0)
{
count ++;
s+=n;
if (n>max)
{
max = n;
}
if (n<min)
{
min = n;
}
cout<< "Please enter a number : ";
cin>>n;
}
cout<<"ZERO DETECTED!\n\n"<<endl;
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
//avg = (float) s/count ;
cout<<"Average: "<<(float) s/count<<endl; //NOTE NOTE NOTE NOTE
return 0;
}