0

Why the code didn't give the right answer?

https://code.sololearn.com/cN2JR2qKO01H/?ref=app I'm doing an exercise on run.codes in C language, where the inputs are 1.88 and M. The output is supposed to be 78.676, but it is 78.674. I'm new in programming and don't speak English very well, so sorry if I write something wrong.

7th Apr 2019, 9:22 PM
Mariana Ferreira
2 Respuestas
+ 1
If you check value 1.88 with printf("%f\n", h); before w = (72.70 * h) - 58.00; you will see 1.879974 I don't know why (if you check before scanf("%s", &g); you will see 1.880000). But with doubles no problem, so this code works: #include <stdio.h> int main() { double h, w; char g; scanf("%lf" ,&h); scanf("%s" ,&g); if(g=='M') { printf("%lf\n", h); w = (72.70 * h); printf("%.3lf", w); } else if(g=='F') { printf("%lf\n", h); w = (62.10 * h) - 44.70; printf("%.3lf", w); } } May be it is because of memory layout of this variables after two scanf functions.
7th Apr 2019, 10:26 PM
Владимир Землянушкин
Владимир Землянушкин - avatar
+ 4
It has to with the precision of float. Double has 2x more precision than float. https://www.google.de/amp/s/www.geeksforgeeks.org/difference-float-double-c-cpp/amp/
7th Apr 2019, 10:28 PM
Denise Roßberg
Denise Roßberg - avatar