"...The numbers I input are (1,2,3,4,5,6,7,8,9,10) Instead of the average its giving me 2,4,6,8.10. How do I correct this?..."
Focusing on only the final loop, a few items to consider that will address this issue, and a few others:
Depending on values of numerator and divisor the average might not be exactly correct due to integer division rounding error. if this is an issue for you, the first code snippet addresses it. If not, the following snippets address only the skipping array elements...
As covered, the following code segment in the original post increments i
twice, once in the for()
loop, then later in the i++
statement. The following addresses each of these, also corrects assignment statements, all with with comments...
float sum = 0.0;//to avoid integer division rounding error, use a floating point type
float ave = 0.0;
for (i = 0; i < 10; i++){
//sum += n;//n does not represent the values strore
sum += (float)numberArray[i];
//i++;//not needed, i is incremented in for loop
avg = (sum/i);
printf("Average is: %f\n\n", ave);
// ^ changed from d to f,
// and numberArray[i] to ave
}
Note, if the effects of integer division are acceptable for your purposes, then use the following:
int sum = 0;
int ave = 0;
for (i = 0; i < 10; i++){
sum += numberArray[i];
avg = (sum/i);
printf("Average is: %d\n\n", ave);
}
And, if outputting only the final result is required (rather than all of the intermediate values), move the last two statements to just after the for loop:
for (i = 0; i < 10; i++){
sum += numberArray[i];
}
avg = (sum/i);
printf("Average is: %d\n\n", ave);
"Is it possible to place the given average back into the file? "
The original statement: myFile = fopen("numbers.txt", "r");
opened the file for read only. But placing the resulting average back into the file requires reopening the file for append and using fputs():
...
fclose(myFile);
//add the following...
char sAve[20] = {0};
myFile = fopen("numbers.txt", "a");
if(myFile)
{
sprintf(sAve, "\nAverage is: %f0.6", ave)
fputs(sAve, myFile);
fclose(myFile);
}
return 0;
}