如何在不将哨兵添加到平均值的情况下打破循环?

时间:2012-02-09 05:06:34

标签: c++ loops breakpoints sentinel

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

#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;

}   

2 个答案:

答案 0 :(得分: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;

} 

答案 1 :(得分:0)

可能你需要在

后添加一行
cout<<"The cent equivalent "<<cent<<endl;

添加:

fav += cent;

并更改

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

为:

fav=(float)fav/count;