输出不符合我的预期结果,如何解决

output does not meet my expected result, how to fix it?

本文关键字:何解决 解决 我的 不符合 结果 输出      更新时间:2023-10-16

>我的预期结果是平均值=73.5,我将平均值的类型设置为双精度,但结果为73有什么问题?

  #include <iostream>
  using namespace std;
  int main(){
int x=0;
int total=0;
double average=0;
int counter=0;
cout<<"Question 1"<<endl<<"Enter integer(-100 to end);";
cin>>x;
 if (x!=-100)
 {
     for(;x!=-100;counter++)
     {
         total=total+x;
         cin>>x;
     }
      average = total/counter;
 }
 cout<<"The average is:"<<average<<endl;

 return 0 ;

}

您正在执行整数计算。将其中一个整数转换为双精度:

average = ((double)total)/counter;

整数运算产生整数作为结果。在 C 和 C++ 中,它们永远不会产生浮点结果。您需要在计算中涉及浮点值,例如

average = (1.0 * total) / counter;