Reputation: 1
I'm pretty stumped on this problem. My totaldistance is not calculating correctly. I'm not sure if this is because I set my loop up incorrectly or if I'm doing something else wrong. I'm getting an average of -0
each time. I printed printf(" total distance = %lf , dailyflights = %d\n", totaldistance, dailyflights);
before the average calculation to determine that it was the totaldistance
that isn't calculating correctly and not the average.
An example of the desired output:
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.
my code:
//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;
}
Upvotes: 0
Views: 138
Reputation: 75062
You have to use %lf
instead of %ld
to read the value of double
to distance
with scanf
.
You should use %f
instead of %lf
to printing values of double
with printf
since float
value is automatically expanded and there are no needs to distinguish between them.
Also, before the inner loop, you need to set totaldistance = 0.0;
so that you accumulate each day's flights separately from each other day's flights to get the average distance computation correct.
Upvotes: 2