簡體   English   中英

我對我的輸出感到困惑,該輸出給出了用戶輸入的數字的總和的最接近平均值(將小數點四舍五入為整數)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM