【问题标题】:In c++, how do I properly use setprecision in this case? (It keeps on rounding off my results)在 c++ 中,在这种情况下如何正确使用 setprecision? (它不断完善我的结果)
【发布时间】:2022-01-15 18:24:31
【问题描述】:

我的代码的主要目标是从用户那里获取输入,将其放入一个大小为 10 的数组中,识别用户给定的数组中的最低元素,打印所有元素的总和数组,删除最小的数字并计算数组内剩余元素的平均值。我的主要问题是当我尝试打印剩余 9 个数字的平均值时(最小的数字被删除),结果几乎总是四舍五入,否则它会自动将 5.00 添加到结果中。

我使用变量 ave 打印剩余 9 个数字的平均值,并使用 setprecision(2) 将小数位变为 2 (0.00)。我该如何解决?谢谢!

您尝试运行代码时的结果是: enter image description here

#include<iostream>
#include<iomanip>
using namespace std;


int main()
{
int dim=10;
int list[dim];
int i;  
int sum;
int newsum;
double ave;

int smallest = 0;
int temp;


cout<<"enter number: "<<endl; // takes input
for(int i = 0; i<dim; i++)
{
    cout<<"loc["<<i<<"] ";
    cin>>list[i];
}

smallest = list[0];

for(int i=1; i<=10; i++) // gets the lowest num
{
    temp = list[i];
    if (temp < smallest) 
    {
        smallest = temp;
    }
}

cout<<"lowest numb is: "<<smallest<<endl; // displays the lowest num
 // tries to replace the element from the list[] array with the value of 0



    
for(int i=0; i<10; i++) // solves the sum of all numbers
{
    sum+=list[i];

}
cout<< fixed << showpoint;
cout<< setprecision(2); // tells the code to print value in 2 decimal places (0.00)
ave = ((sum - smallest)/9); //computes the average with total minus lowest element in array
cout<<"sum is: "<<sum<<endl; 
cout<<"average is: "<< ave << endl; // displays values

}

【问题讨论】:

  • int dim=10; int list[dim]; -- 这不是有效的 C++。 dim 必须是 const int,而不仅仅是 int。第二:for(int i=1; i&lt;=10; i++) -- 问问自己在该循环的最后一次迭代和list[i] 上发生了什么。 i 的值是多少?任何使用&lt;= 作为条件的循环都将被视为错误。

标签: c++


【解决方案1】:
  1. for(int i=1; i&lt;=10; i++) 还会检查 list[10],这是未定义的,会导致一些不可预测的值。 第 11 个元素的值可能是最小的元素,从而导致错误的结果。

  2. sum 应该初始化为0,不初始化也将是未定义的并导致错误。

  3. setprecision(N) 表示使用N 总数,而不仅仅是小数分隔符之后: https://www.cplusplus.com/reference/iomanip/setprecision/ 它会跳过任何尾随零,除非你也使用std::fixed

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多