![](/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.