0

按照现在的代码,哨兵被包括在平均值的计算中。关于如何在不包括哨兵的情况下打破循环的任何指示?

#include <iostream>
using namespace std;
int main ()
{

int fahr=0,cent=0,count=0,fav=0;

while (fahr!=-9999)
{
    count ++;       
    cout<<"Input the fahrenheit temp to be converted to centigrade or enter -9999 "<<endl;
    cin>>fahr;
    cent=(float)(5./9.)*(fahr-32);
    cout<<"The inputed fahr "<<fahr<<endl;  
    cout<<"The cent equivalent "<<cent<<endl;



}
fav=(float)(fav+fahr)/count;
    cout<<"Average"<<fav<<endl;
return 0;

}   
4

2 回答 2

1

使代码在无限循环中运行,如果看到 -9999,请使用 break 终止循环。

#include <iostream>
using namespace std;
int main ()
{

int fahr=0,cent=0,count=0,fav=0;

while (true)
{
    count ++;       
    cout<<"Input the fahrenheit temp to be converted to centigrade or enter -9999 "<<endl;
    cin>>fahr;

    if (fahr == -9999)
       break;

    cent=(float)(5./9.)*(fahr-32);
    cout<<"The inputed fahr "<<fahr<<endl;  
    cout<<"The cent equivalent "<<cent<<endl;
}

fav=(float)(fav+fahr)/count;
cout<<"Average"<<fav<<endl;
return 0;

} 
于 2012-02-09T05:14:09.397 回答
0

可能您需要在之后再添加一行

cout<<"The cent equivalent "<<cent<<endl;

添加:

fav += cent;

和改变

fav=(float)(fav+fahr)/count;

至:

fav=(float)fav/count;
于 2012-02-09T05:20:13.580 回答