gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:10:36 25 4
gpt4 key购买 nike

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

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

}

最佳答案

使代码在无限循环中运行,如果看到 -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;

}

关于c++ - 我们如何在不将哨兵添加到平均值的情况下打破循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9205708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com