The following block of code works well accept for the fact that when it attempts to calculate the average temperature in a given amount of days, it does some math wrong. I put in a printf statement to isolate the problem and it seems to be adding wrong. Example; when I put in 6 -2 8 and -1, it adds them up and gets 13.50. I think its a casting problem but whenever I try to solve that I make it worse. How do I fix this?
#include
#define SIZE 10
int main() {
int averageDays = 0;
double average = 0.0;
int high[SIZE];
int low[SIZE];
int days;
int counter;
int hottestTemp = -40;
int lowestTemp = 40;
int highestDay, lowestDay;
printf("---=== IPC Temperature Calculator V2.0 ===---n");
printf("Please enter the number of days, between 3 and 10, inclusive: ");
scanf("%d", &days);
while (days < 3 || days > 10) {
printf("nInvalid entry, please enter a number between 3 and 10, inclusive: ");
scanf("%d", &days);
}
printf("n"); // this is just for spacing
for (counter = 0; counter < days; counter++) {
printf("Day %d - High: ", counter + 1);
scanf("%d", &high[counter]);
printf("Day %d - Low: ", counter + 1);
scanf("%d", &low[counter]);
}
printf("nDay Hi Low");
for (counter = 0; counter < days; counter++) {
printf("n%d %d %d", counter + 1, high[counter], low[counter]);
}
printf("nn");
for (counter = 0; counter < days; counter++) {
if (hottestTemp < high[counter]) {
hottestTemp = high[counter];
highestDay = counter + 1;
}
if (lowestTemp > low[counter]) {
lowestTemp = low[counter];
lowestDay = counter + 1;
}
}
printf("The highest temperature was: %d, on day %dn", hottestTemp, highestDay);
printf("The lowest temperature was: %d, on day %dn", lowestTemp, lowestDay);
while (averageDays > -1) {
printf("nEnter a Number Between 1 and %d to see the average temperature for the entered number of days, enter a negative number to exit: ", days);
scanf("%d", &averageDays);
while (averageDays > days) {
printf("nInvalid entry, please enter a number between 1 and %d, inclusive: ", days);
scanf("%d", &averageDays);
}
for (counter = 0; counter < averageDays; counter++) {
average = average + (double)high[counter] + (double)low[counter];
}
printf("%.2lf, %d", average, averageDays);
average = average / (averageDays * 2);
if (averageDays > 0) {
printf("nThe average temperature up to day %d is: %.2lfn", averageDays, average);
}
else
{
printf("nGoodbye!n");
}
}
return 0;
}