# extraño acerca de la precisión de salida de la función "printf"

``````    printf("%.2lf\n",odd);                        //(1)
printf("%.2lf\n",37.975);                     //(2)
printf("%.2lf\n",(odd*0.65 -1)*2);            //(3)
printf("%.3lf\n",(odd*0.65 -1)*2);            //(4)
``````

A continuación se muestra el resultado:

30.75

37.98

37.97

37.975

Why the output of expression(3) is not 37.98 ?

I use g++.

preguntado el 10 de marzo de 12 a las 06:03

Probably because that `0.65` is actually slightly less than `0.65`: docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html -

## 3 Respuestas

This is likely due to floating point rounding errors. The result of `(odd * 0.65 - 1) * 2` es probable `37.97499999999999` or something close to (but less than) `37.975`. By the usual rounding rules, this is rounded down to `37.97` en la salida.

respondido 10 mar '12, 06:03

Since I get a different result with `odd` set to 37.975, the reason is most likely that `odd` is ligeramente menos than 30.75 in your calculation (you're not showing it un-rounded in your question) which makes the calculation result in a number slightly less than 37.975.

respondido 10 mar '12, 06:03

Computer (binary) floating point can't represent decimal numbers precisely, just like decimal floating point can't represent some fractions. For example 1/9 = .11111111111.... Display more digits of precision, and you'll see what happened.

Since you didn't provide the value of `odd`, I chose one that gave the same result:

``````#include <stdio.h>

int main()
{
double odd = 30.7499;
printf("%.2lf\n",odd);                        //(1)
printf("%.2lf\n",37.975);                     //(2)
printf("%.2lf\n",(odd*0.65 -1)*2);            //(3)
printf("%.3lf\n",(odd*0.65 -1)*2);            //(4)
printf("%.20lf\n",odd);                        //(1)
printf("%.20lf\n",37.975);                     //(2)
printf("%.20lf\n",(odd*0.65 -1)*2);            //(3)
printf("%.20lf\n",(odd*0.65 -1)*2);            //(4)
return 0;
}
``````

### Salida

``````30.75
37.98
37.97
37.975
30.74990000000000000000
37.97500000000000100000
37.97487000000000300000
37.97487000000000300000
``````

respondido 10 mar '12, 06:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.