I need to print the sum and average of user input array. So if user inputs 2,4,6,9,10 it should print 6. However, after the loop ended my printf is not printing anything.
Even if I put the printf inside the array it only prints out 0.
#include <stdio.h>
#include <math.h>
int main()
{
int i;
double num[6],average, sum=0, closest;
printf("Enter 6 doubles\n");
for (i=0; i<6; i++)
{
scanf("%lf",&num[i]);
sum += num[i];
}
average = sum/i;
printf("Average %d", average);
}
There are a few things you need to do in the code. You should be making sure they enter 6 numbers (in your opening post you only list 5, this will create problems). I changed the printing to use this and stripped out some variables that you don't use.
#include <stdio.h>
#include <math.h>
int main()
{
int i;
double sum = 0;
printf("Enter 6 doubles\n");
for (i = 0; i < 6; i++)
{
double value;
scanf("%lf", &value);
sum += value;
}
printf("Average = %f", sum / i);
}
Enter 6 doubles:
2 4 6 9 10 10
Average = 6.833333
This question is not a duplicate but I found the answer on StackOverflow here
The stdout stream is buffered, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:
Print to stderr instead using fprintf:
fprintf(stderr, "I will be printed immediately");
Flush stdout whenever you need it to using fflush:
printf("Buffered, will be flushed"); fflush(stdout); // Will now print everything in the stdout buffer
You can also disable buffering on stdout by using setbuf:
setbuf(stdout, NULL);
Then regarding your code, here are a few remarks:
man 3 printf
the conversion specifier f
already convert to double floating point values, so no need for a length modifer flag. %d
you will lose the real valued part, consider using %f
as well. the following proposed code:
main()
printf()
and now, the proposed code:
#include <stdio.h> // printf(), scanf(), perror()
//#include <math.h>
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MAX_ENTRIES 6
int main( void )
{
//int i;
// double num[6];
double num;
double average;
double sum=0.0;
// double closest;
printf("Enter %d doubles\n", MAX_ENTRIES );
for (int i=0; i< MAX_ENTRIES; i++)
{
if( scanf( "%lf", &num ) != 1 )
{
fprintf( stderr, "scanf for number failed\n" );
exit( EXIT_FAILURE );
}
sum += num;
}
average = sum / MAX_ENTRIES;
printf("Average %f\n", average);
}
a typical run of the code results in:
Enter 6 doubles
1.0
2.0
3.0
4.0
5.0
6.0
Average 3.500000
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.