float 变量不满足条件 (C) [英] float variable doesn't meet the conditions (C)

查看:39
本文介绍了float 变量不满足条件 (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)
");
scanf("%f", &gap);
while ((gap < 0.00002) || (gap > 0.99999))
{
printf("Enter required Leibniz gap.(Between 0.00001 to 1.00000)
");
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.

推荐答案

floats 不能为每个可能的数字存储精确的值(0-1 之间的无限数字因此不可能).由于您正在经历的实现,将 0.00002 分配给浮点数将具有不同但非常接近的数字.随着数量的增加,精度会降低.

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; 在内部表示 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.

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

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