Psychobagger Psychobagger - 1 year ago 43
C Question

Assigning changing numbers to a single variable

Just screwing around in C... wanted to make a program that calculated the average of whatever numbers the user input.

The program works fine, I just can't 'logic' out how to do the next part.

I need to be able to take each number they input and average them, using the number they input for the first scanf to divide by. I only assigned one variable for each number they input, but after about a second of looking at the code I realized I would need to use calculus or some programming trick to be able to do this (effectively) infinitely. Basically, the variable needs to change each time so the sum can be taken then divided over the total number of numbers. I'm ranting...

Can anyone who can understand my stupid problem give me some pointers? That'd be great...

My includes and the int main () are there, don't worry. Just felt no need to clutter it with already known stuff. Also, I don't do shorthand anything- I feel no need to as of now.

// Base variables
int iUserReq, iNumCounter = 0;
// Each individual number
double dUserNum = 0.0;
// Calculation
double dNumSum = 0.0, dNumAvg = 0.0;

// Ask user for the number of variables to be averaged... will come in handy
printf("Please input how many numbers you would like to average together, as a number. For example, 10.\nTry to keep it low, because you're going to be putting them all in manually. > ");
scanf("%d", &iUserReq);

// If user inputs 0 or negative number, keep asking until they put in a positive number
while(iUserReq <= 0)
printf("Please input a number greater than 0. > ");
scanf("%d", &iUserReq);

// This adds a counter, so for the number of numbers the user wants to average, it will loop that many times and ask for an input that many times
// I.e. they want to average 10 numbers, it asks for 10 numbers

while(iNumCounter < iUserReq)
printf("Please input number. > ");
scanf("%lf", &dUserNum);
iNumCounter = iNumCounter + 1;

return 0;



Answer Source

OK, I'm going to bite and give you the solution.

At the top of your program:

double sum = 0.0;

After you scanf() for each number:

sum += dUserNum;

Just before return 0:

printf("%f\n", sum / iUserReq);

Do you understand why this works?