ImperfectLion ImperfectLion - 4 months ago 26
C Question

Calculations Not working properly

I am learning C from a book called "C by Example"

At the end of each chapter there is an exercise to complete. As you can see from the code below, the exercise is written at the top

/* Chapter 7 Review Exercises #2
- You are a college professor and you have to get the average grades for 10 students. Write a program which prompts you for 10 different grades and then
displays their average */

#include <stdio.h>

int main()
{

float score1, score2, score3, score4, score5, score6, score7, score8, score9, score10;

float average = score1+score2+score3+score4+score5+score6+score7+score8+score9+score10/10;

printf("Please input the scores of the students: \n");
scanf(" %f",&score1);
scanf(" %f",&score2);
scanf(" %f",&score3);
scanf(" %f",&score4);
scanf(" %f",&score5);
scanf(" %f",&score6);
scanf(" %f",&score7);
scanf(" %f",&score8);
scanf(" %f",&score9);
scanf(" %f",&score10);

printf("The average score is: %.2f" , average);

return 0;

}


The problem here is that every time I input numbers (when running the code) It always gives me a HUGE number back (like at least 20 numbers long)

Is there a way to limit the number, or am I doing something wrong?

Answer

The following code will work. Your code doesn't work because you try to calculate numbers before they are scanned. Still you have to remember that C keeps order of the operations so / is executed before +. Add missing brackets (). In C the code is processed from top to the bottom!

#include <stdio.h>
int main() {

    float score1, score2, score3, score4, score5, score6, score7, score8, score9, score10;

    printf("Please input the scores of the students: \n");
    scanf(" %f",&score1);
    scanf(" %f",&score2);
    scanf(" %f",&score3);
    scanf(" %f",&score4);
    scanf(" %f",&score5);
    scanf(" %f",&score6);
    scanf(" %f",&score7);
    scanf(" %f",&score8);
    scanf(" %f",&score9);
    scanf(" %f",&score10);

    float average = (score1+score2+score3+score4+score5+score6+score7+score8+score9+score10)/10;
    printf("The average score is: %.2f" , average);

    return 0;

}