【发布时间】: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<=10; i++)-- 问问自己在该循环的最后一次迭代和list[i]上发生了什么。i的值是多少?任何使用<=作为条件的循环都将被视为错误。
标签: c++