浮点变量不符合条件(C) [英] float variable doesn't meet the conditions (C)

查看:157
本文介绍了浮点变量不符合条件(C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让用户输入1.00000之间的数字0.00001,而不是边缘纳入浮点型变量。我可以假设一个点之后的用户不会打字超过5个号码。
现在,这里是我写的:

I'm trying to get the user to input a number between 1.00000 to 0.00001 while edges not included into a float variable. I can assume that the user isn't typing more than 5 numbers after the dot. now, here is what I have written:

printf("Enter required Leibniz gap.(Between 0.00001 to 1.00000)\n");
scanf("%f", &gap);
while ((gap < 0.00002) || (gap > 0.99999))
{
printf("Enter required Leibniz gap.(Between 0.00001 to 1.00000)\n");
scanf("%f", &gap);
}

现在,当我打字的最小数量的可能:0.00002在被陷在while循环。
当我运行调试器,我看到0.00002存储在浮动的变量此值:1.99999995e-005
任何人都可以澄清我什么我做错了?为什么不是0.00002会议的条件?这是什么1.99999995e-005的事情。

now, when I'm typing the smallest number possible: 0.00002 in getting stuck in the while loop. when I run the debugger I saw that 0.00002 is stored with this value in the float variable: 1.99999995e-005 anybody can clarify for me what am I doing wrong? why isn't 0.00002 meeting the conditions? what is this "1.99999995e-005" thing.

推荐答案

浮动是不能够0-1之间为每个可能数量存储精确值(无限的数字因此不可能)。分配0.00002到一个浮动都会有不同,但非常接近数因实施这是你正在经历。 precision会随着数量的增长。

floats are not capable of storing exact values for every possible number (infinite numbers between 0-1 therefore impossible). Assigning 0.00002 to a float will have a different but really close number due to the implementation which is what you are experiencing. Precision decreases as the number grows.

所以你不能直接比较两个亲密的花车和拥有健康的结果。

So you can't directly compare two close floats and have healthy results.

浮动点的详细信息,可以发现这个维基百科页面

More information on floating points can be found on this Wikipedia page.

你可以做的是模拟定点数学。有一个 INT N = 100000; 重新present 1.00000 内部(1000 - > 0.001等等)和做相应的计算或使用定点数学库。

What you could do is emulate fixed point math. Have an int n = 100000; to represent 1.00000 internally (1000 -> 0.001 and such) and do calculations accordingly or use a fixed point math library.

这篇关于浮点变量不符合条件(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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