the following proposed code:
- uses a proper signature for
main()
- corrects the format used in the call to
printf()
- appends a '\n' to the format string in 'printf()' so the data is immediately output rather than after the program exits
- gives 'magic' numbers (I.E. 6) meaningful names
- properly checks for I/O errors and handles any such error
- eliminates unneeded variables
- does not include header files those contents are not used
- documents why each header file is included
- properly limits the scope of local variable 'i'
- cleanly compiles
- performs the desired functionality
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
printf("Average %d", average);
you need to use the format specifier%f
for printing doubles. If you use gcc as compiler you could compile using the compiler flag-Wall
to see the respective warning. – user10835998\n
too -->printf("Average %e\n", average);
"%e"
is more informative than"%e"
for debugging. – chux - Reinstate Monica