![](/img/trans.png)
[英]How can I get rid of zeros, if decimal is entered it prints decimal, but if whole number is entered it prints .00?
[英]I am confused about my output that gives the closest average of sum of numbers entered by the user.(rounds the decimal to a whole number)
完成以下程序,找到数组中平均数最接近的数字。 例如,数组{2、4、6、3、9、10}的平均值为5.666667,并且数组中与平均值最接近的数为6。请注意,最接近的数可以大于或小于平均值。
#include <stdio.h>
#include <math.h>
int main()
{
int i;
double num[6],average, sum=0, closest;
printf("Enter 6 doubles\n"); //2,4,6,9,3,10
for (i=0; i<6; i++)
scanf("%lf",&num[i]);
//professor's code
for (i=0; i<6; i++)
sum += num[i]; //sum=34
average=sum/6; //5.6666667
closest = num[0]; //why are we even using this??? //initialize?
for (i=0; i<6; i++)
if(fabs(num[i]-average) < fabs(closest-average)) //|6-5.7|<|0-5.7|-> 0.7<5.7->true
closest = num[i]; // why is it giving 6??
//where is it being rounded to the closest number??
//professor's code ends
printf("Closest is %lf\n", closest);
return(0);
}
//Output:
//Closest is 6
您的标题和代码注释表明您认为该程序(总是)返回最接近其输入平均值的整数。 它不是。 它返回输入最接近平均值的全部投入。 如果所有输入都是整数,那当然就是整数,但是您将它们输入为浮点数,因此它们不必是整数。 因此,输出也不必为一。
例如,如果这些输入出现在您的程序中:
1 2 2 2 2 1.8
,它将接受它们并输出
最近的是1.800000
。 此外,不确定输出是否特别接近平均值。 例如,尝试以下输入:
1 1 1 1 1 1000000
。 你应该得到
最近是1.000000
。 这是一个整数,但比平均值少了166666。
关于代码中嵌入的问题:
closest = num[0]; //why are we even using this??? //initialize?
紧接着,在代码回路寻找更接近平均投入比closest
的。 这是毫无意义的,如果closest
尚未分配的值,它可能会导致错误的结果,如果closest
不包含等于一个输入的值。 当然, closest
起始值与num[0]
相同,如果循环从索引1而不是索引0开始测试,则输出将相同。
//where is it being rounded to the closest number??
它不是四舍五入的。 此时, closest
值已包含等于输入之一的值。 不需要四舍五入,实际上四舍五入会产生不在输入范围之内的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.