Dilanka Madhawa
Dilanka Madhawa

Reputation: 9

error in float variable-c

friends i am a computer science student and my lecturer given me a assignment to write a program to input 20 numbers into array and count the total and average of the marks.so i have written the above code as answer.now when i check the answers with inputs there is a small error in average.if the correct average is 48.59,the program gives average as 48.00.i tried to solve the problem and i was unable to do it.can someone help me?

im using CODEBLOCKs to write programs.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int grades[20];
   int a,b,c,d,tot=0,high=0;
   float avg=0;
   for(a=0;a<20;a++)
    {
        printf("Input the Mark : ");
        scanf("%d",&d);

        if(d>=0&&d<=100)
            grades[a]=d;
        else
    {
            printf("OUT OF RANGE.PLEASE INPUT A VALID NUMBER.\n");
            a--;
    }
}
for(b=0;b<20;b++)
{
    tot=tot+grades[b];
}

avg=tot/20;

high=grades[0];
for(c=0;c<20;c++)
{
    if(high<grades[c])
        high=grades[c];
}
printf("The Total Value is : %d\nThe Average is : %.02f\nHighest Value is : %d",tot,avg,high);

}

Upvotes: 0

Views: 1289

Answers (2)

Matias Valenzuela
Matias Valenzuela

Reputation: 21

avg=tot/20;

The problem here is that tot and 20 are integers. The arithmetic division of tot/20 will produce another integer, not a floating point number. The result will be promoted to floating point before being assigned to the float variable avg, but the decimal fraction does not exist, because of the integer division.

The solution is very simple.

avg = tot/20.0

By adding a decimal fraction to the divisor, that is changing 20 to 20.0, the division is promoted to floating point division, rather than integer division, because one of the operands is a floating point number (20.0).

Alternatively, you could cast one of the integers as a floating point.

avg = (float)tot/20

What that does is to convert the integer tot into a floating point number before the division takes place, having the same effect as appending a decimal fraction to the other operand.

Also, in this printf format specifier for the floating point value "%.02f", the leading zero is unnecessary. A specifier of "%.2f" is more correct. However, this has no effect on the output.

I hope it helps! Have a great day!

Upvotes: 1

NPE
NPE

Reputation: 500167

The following uses integer division (even though you store the result in a floating-point variable):

avg=tot/20;

To force floating-point division, use:

avg=tot/20.0;

Upvotes: 7

Related Questions