You are using a version without Ads of this website. Please, consider donating:

### While Statement

I have searched my book and the internet for help with this code and couldn't find an example to help.

I need to prompt the user for a number of temperatures. Then the user will input that number of temperatures. Lastly, my code will find the sum of those temperatures the user entered.

The code compiles correctly, the output isn't working properly. (Which is where i need help)

 ``12345678910111213141516171819202122232425262728`` ``````#include int main(void) { int num_temps; int temperature; int run_sum = 0; double avg; printf("What is the quantity of temps: "); /*Prompt user*/ scanf("%d", &num_temps); while ( run_sum < num_temps ) { printf("\nEnter a temperature: "); /*prompt user*/ scanf("%d", &temperature); run_sum = run_sum + temperature; /*Add Temperatures in sum*/ run_sum++; } avg = run_sum / num_temps; /*Averaged temperature*/ printf("\nThe average is %.2f\n\n", avg); return(0); } ``````
If num_temps is the number of temperature data points and run_sum is the total sum of the temperatures, then the while loop will probably break early. I suggest using a counter variable instead of run_sum.

Consider the logic of the current code:
--Uses num_temps as maximum temperature sum.
--Compares the total temperature sum plus 1 to the number of temperature data points.
--Does not iterate according to the number of data points
--run_sum will always be larger than the total sum of the temperatures.
--Therefore, average will be incorrect.
Your program seems to be completely C and not using any of the C++ features.

One issue is that in line 22, you may not get what you expect. The division will be performed as integer division resulting in an integer value that will then be assigned to avg which is a double. For example if run_sum is 54 and num_temps is 10, avg will be 5.0.

The C solution is to cast one of the values in the division to double which will then change the calculation to be a double division.
` avg = (double) run_sum / num_temps; /*Averaged temperature*/`
Topic archived. No new replies allowed.