Search code examples
cfloating-pointstdio

Unable to Calculate Correct Average


C language, stdio.h library

Sample code:

float avg;
avg = 3 / 2;
printf("Average: %.2f", avg);

From the code above I expect the following output:

Average = 1.50

But instead I get:

Average = 1.00

Why is this? And how do I get the correct output?


Solution

  • #include <stdio.h>
    
    int main(void) {
    float avg;
    avg = (float) 3 / 2;
    printf("Average: %.2f", avg);
    
        return 0;
    }