浮点数丢失精度 [英] float number loosing percision

查看:97
本文介绍了浮点数丢失精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我正在使用Visual Studio 2010在本地C语言中编写以下代码:

Hello,
i am writing in native C, using visual studio 2010 the following code:

float temp = 0;
int temp2 = 0
printf("Enter decimal number between 30.00 to 1000.00\n");
scanf("%f", &temp);
temp2 = (int)(temp*100);




问题是当我尝试将数字转换为
时,我失去了精确度 一个整数.

例如,如果用户输入30.15
temp2获得值3014;




the problem is that i loose percision when i try to cast the number into
an integer.

for example if user enters 30.15
temp2 gets the value 3014;

how can i overcome this issue ?!

推荐答案

我实际上是在C#中尝试过的,但是我认为数学库是相同的.
I actually tried it in C#, but I think the math lib is the same.
string s = "30.15";
float f = float.Parse(s);
int i = (int) (f * 100);
float g = f * 100;
int j = (int) (g);
MessageBox.Show(i.ToString() + ":" + j.ToString());

提供消息框

Gives the message box

3014:3015

这有点奇怪,但是这意味着您值得尝试自己创建一个本地浮动对象...

Which is a little odd, but means that it may be worth your trying to create a local float yourself...


它不会失去精度,它从来没有首先.如果计算出30.15的二进制表示形式,则会发现它的浮点数表示的位数小于30.15.实际上,因为0.15并不是可以用相乘的0.5的幂进行累加来表示的分数,所以您将永远无法获得所需的精度.

那你该怎么办?

好吧,您可以做的一件事就是使用不会丢失精度的数据类型,例如一双整数.因此,您将使用类似以下内容的内容进行阅读:

It''s not loosing precision, it never had it in the first place. If you work out what the binary representation of 30.15 you''ll find out that it''s represented as something a bit less than 30.15 for the number of bits you''ve got in a float. In fact as 0.15 is not a fraction that can be represented by summing successive powers of 0.5 you''ll never get get the sort of precision you''re after.

So what can you do about it?

Well one thing you could do is use a data type that doesn''t loose precision, e.g. a pair of ints. So you''d read in using something like:

int whole_part = 0;
int hundredths = 0;

scanf( "%d.%d", &whole_part, &hundredths );

int temp = whole_part * 100 + hundredths;



基本上,道德是现实世界中的浮点数(例如,当您写30.15时,您实际上是在说半开范围为30.145到30.155的数字"),计算机也是如此.因此,在需要很高的精度时不要使用它们,在可能或至少知道它们如何工作的地方使用定点数,这样就可以在问题发生时解决问题.

干杯,



PS:请记住检查scanf的返回值,您将要在块的开头声明temp,而不是像我一样执行其他一些语句之后.



Basically the moral is floating point numbers in the real world are approximations (e.g. when you write 30.15 you''re actually saying "a number in the half open range 30.145 to 30.155") and computers are no different. So don''t use them when you need a lot of precision, use fixed point numbers where you can or at least know how they work so you can fix problems when they happen.

Cheers,

Ash

PS: Remember to check the return value of scanf and you''ll want to declare temp at the start of a block, not after carrying out some other statements the way I have.


演员不圆.它只会减少数字.
只需在投射前添加0.5.
The cast does not round. It only cuts away the numbers.
Simple add 0.5 before casting.


这篇关于浮点数丢失精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆