Divisions miscalculating in C

Asked

Viewed 107 times

3

#include <stdio.h>

int main()
{
    double A, B;
    double MEDIA;
    scanf("%f", &A);
    scanf("%f", &B);
    MEDIA = (A + B)/2;
    printf("MEDIA = %5f", MEDIA);
    return 0;
}

In this program I have already understood that the problem is that the scanf() cannot read variables double. So, by changing the primitive type of variables A and B for float, instead of double, the program works correctly as it should. But I NEED you to read the variables in double. I don’t know how to solve, I don’t even know if there’s any way to solve, since for some reason, I didn’t find anything talking about reading variables double.

1 answer

5


I see no need for this kind of data to be double, but I will consider that it is a senseless requirement of exercise (actually can give slight difference, if need of accuracy neither of these two types can be used), then the correct is to use the format of long float to receive the data as double. I took the opportunity to change the variable name to stay within the standard that is used.

#include <stdio.h>

int main() {
    double a, b;
    scanf("%lf", &a);
    scanf("%lf", &b);
    printf("MEDIA = %5f", (a + b) / 2);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Note that in the printf()no need because there is cast automatic. No scanf() cannot happen because it is a pointer that is received.

  • Interesting case that scanf() is different from printf(). In printf() the %f serves for the double by the fact that printf() accepts variable number of parameters, while scanf() uses different masks for float, double and long double.

  • Thank you very much @Maniero. Solved the problem that was in question. But do you believe that was not the problem to be solved in the exercise? I thought that was the problem, and even after I was able to solve this part, this was not the problem I was not allowed to pass in the exercise. But thank you so much anyway.

  • I also did not understand this part of it being necessary to read the variables in double, but since the exercise asks so, I will not doubt, kkkk.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.