c++ - float类型精度问题
高洛峰
高洛峰 2017-04-17 11:53:23
0
6
477

我自己编写那个摄氏转华氏的计算如下:

nclude<stdio.h>

void main()
 { 
 float c, f; printf("Please enter a C: \n");
 scanf("%f",&c);
 f = 1.8*c + 32; 
 printf("F is:%f",f); 
} 

但是,当我输入25.8时,结果给的是78.440002% 想问一下,为什么会多出来最后那个0002和最后的%。?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(6)
伊谢尔伦

The main problem is that computers use binary to represent data:

二进制的 0.1 是十进制的 0.5 
 0.1   <=> 0.5
 0.01  <=> 0.25
 0.001 <=> 0.125
 .....

But there is a problem when we represent 0.8 in decimal
0.8 = 0.5 + 0.25 + 0.03125 + 0.01526 + ... So expressed in binary it is 0.11001100... This is infinitely long. But the computer can only represent a finite length. For example, 0.110011. When this limited binary is converted into the decimal system we are used to, it is 0.796875. That is to say, we want to save 0.8, but in fact, the computer saves 0.796875 (the computer may save The binary data is longer and is just more accurate), so the situation in your code occurs.

The solution is not to output the calculation results and just use an approximation. If you need greater precision, use higher-precision floating point numbers.
What you need to remember is that computers store floating point numbers imprecisely.

Peter_Zhu

printf does not specify the decimal point length, f% displays the integer part and 6 decimal places by default
To be more precise, use lf

Peter_Zhu

The questioner needs to understand the basic knowledge about floating point numbers. This article explains it better http://cenalulu.github.io/linux/about-denormalized-float-number/

Peter_Zhu

Most floating point numbers cannot be represented accurately in computers. You can refer to the BigDecimal class in Java to represent fixed-point numbers

左手右手慢动作

The float type has a default precision and generally cannot accurately represent a certain value

迷茫

I ran your program, and there is no % at the end of the output. I guess that is your command line prompt.
Just like the F is:78.440002MacAir~/Temp $ in my MacAir.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template