1

Could someone explain to me why the "scan" function is not working in the following code? What do I do to fix the problem? Thanks!

int main() {
    int age, sumage;
    float mean;
    sumage = 0;
    for (int a = 1; a <= 20; a = a + 1) {
        printf("Enter age: \n");
        scanf("%d", &age);
        sumage = sumage + age;
    }
    mean = sumage/20;
    printf("mean = é %f \n" , mean);
    return 0;
}
jww
  • 97,681
  • 90
  • 411
  • 885
TRF
  • 11
  • 1

2 Answers2

1
mean = sumage/20;

Here sumage is an integer. Thus the division is integer division.

Change into (float)sumage / 20.0 to get expected result.

timrau
  • 22,578
  • 4
  • 51
  • 64
  • Strictly speaking, it should be `(float)sumage / 20.0f` or just `sumage / 20.0f`. The double literal will enforce the division to be done with double precision, which is then truncated to float. Makes the program needlessly slow unless the compiler manages to optimize. – Lundin Nov 17 '14 at 07:49
  • I want to read 20 ages, but scanf just reads the first one. The application keeps running, but nothing happens anymore. I tried everything, all var integers, double, it wouldn't work. The application basically stops at scanf. – TRF Nov 18 '14 at 13:23
0

You are attempting to fill a float with an integer value:

mean = sumage/20;

needs a cast to float to store the value as a float:

mean = (float) sumage/20;

Bottom line, int/int = int, unless cast otherwise. The C99 reference for arithmetic conversion is:

6.3.1.8 Usual arithmetic conversions

Otherwise, if the corresponding real type of either operand is float, the other operand is converted, without change of type domain, to a type whose corresponding real type is float.51)

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85