我非常難倒這個問題。我的總距離計算不正確。我不確定這是因爲我錯誤地設置了我的循環,還是因爲我做了其他錯誤。每次我平均得到-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;
}
您需要在每個內部循環開始之前將'totaldistance'設置爲零。 –