samedi 1 octobre 2016

Programming C Loop Incorrect calculation

I am writing a C code that calculates the average of the marks. It asks the user to input the number of marks between 3 and 40. If the user doesn't input between 3 and 40, it asks again. It then asks for the mark percentages and adds it all up to calculate the average. Here's my code:

#include<stdio.h> 
int main()
{
int number_marks,i, a=1;
float grade, total, average;

    printf("Please enter the number of marks (between 3 and 40): ");
    scanf("%d", &number_marks);

if(number_marks>3 || number_marks<40)
{
    do{
    printf("Invalid number, enter a number between 3 and 40 inclusive: ");
    scanf("%d",&number_marks);
    }while(number_marks<3 || number_marks>40);
    for(i=0;i<number_marks;i++)
    {
        printf("%d>",a++);
        scanf("%f",&grade);
     total=grade+grade+grade+grade+grade;
    average= (total/number_marks);
    }
}
printf("The average of all marks in this group is %.1f\n",average);
printf("Program Ended.");
return 0;
}

The problem is the output of the calculation. It seems that it outputs the final grade and does not calculate the average. There's the output:

Please enter the number of marks (between 3 and 40): 2
Invalid number, enter a number between 3 and 40 inclusive: 41
Invalid number, enter a number between 3 and 40 inclusive: 5
1>45
2>90
3>57
4>89
5>32
The average of all marks in this group is 32.0
Program Ended.

Aucun commentaire:

Enregistrer un commentaire