2015-09-27 140 views
0

我非常難倒這個問題。我的總距離計算不正確。我不確定這是因爲我錯誤地設置了我的循環,還是因爲我做了其他錯誤。每次我平均得到-0。我在平均計算之前打印printf(" total distance = %lf , dailyflights = %d\n", totaldistance, dailyflights);,以確定它是不正確計算的totaldistance,而不是平均值。平均不嵌套for循環計算

所需的輸出的一個例子:

How many days has your dragon been practicing? 
3 

How many flights were completed in day #1? 
2 
How long was flight #1? 
10.00 
How long was flight #2? 
15.00 
Day #1: The average distance is 12.500. 

How many flights were completed in day #2? 
3 
How long was flight #1? 
9.50 
How long was flight #2? 
12.00 
How long was flight #3? 
13.25 
Day #2: The average distance is 11.583. 

How many flights were completed in day #3? 
3 
How long was flight #1? 
10.00 
How long was flight #2? 
12.50 
How long was flight #3? 
15.00 
Day #3: The average distance is 12.500. 

我的代碼:

//pre-processor directives 
#include <stdio.h> 

//Main function 
int main() 
{ 
    int days = 0, totaldays, flight_num, dailyflights; 
    double distance, cur_distance = 0, totaldistance = 0, average_dist; 

    printf("How many days has your dragon been practicing?\n"); 
    scanf("%d", &totaldays); 

    for(days=1; days <= totaldays; days++) { 
     printf("How many flights were completed in day #%d?\n", days); 
     scanf("%d", &dailyflights); 

     for (flight_num=1; flight_num <= dailyflights; flight_num++) { 
      printf("How long was flight #%d?\n", flight_num); 
      scanf("%ld", &distance); 
      totaldistance = distance + totaldistance; 
     } 
     printf(" total distance = %lf , dailyflights = %d\n", totaldistance, dailyflights); /*I printed this line to determine what isn't correct and I determined that totaldistance is not calculating correctly*/ 
     average_dist = totaldistance/(float) dailyflights; 
     printf("Day #%d: The average distance is %.3f.\n", days, average_dist); 

    } 

    return 0; 
} 
+1

您需要在每個內部循環開始之前將'totaldistance'設置爲零。 –

回答

2

你必須使用%lf,而不是%lddouble值與scanfdistance

您應該使用%f而不是%lf打印的double值與printf因爲float值自動展開,也沒有需要區分它們。

此外,在內循環之前,您需要設置totaldistance = 0.0;,以便您累計每天的航班與每一天的航班分開,以獲得平均距離計算的正確性。

+0

這些都是好的一點,但只是問題的一部分。該代碼還需要在內循環開始之前將'totaldistance'設置爲'0.0'。 –

+0

謝謝!這解決了所有數字的平均計算。我仍然收到十進制數字的錯誤。該程序將10 + 12.5 + 15解釋爲10 + 12 + 5 + 15,因此在任何有小數的航班的日子裏,我都會得到錯誤的平均值。結合喬納森的建議將totaldistance設置爲0解決了問題 – tonomon

+0

@JonathanLeffler謝謝!這解決了我最後的問題。你能解釋爲什麼重新設置totaldistance爲0是需要的,因爲我真的被難住了。 – tonomon