简体   繁体   English

C++:这个浮点错误问题的解决方案?

[英]C++: Solution to this floating point error problem?

This is an example of my code:这是我的代码示例:

float a = 0.f;
float b = 5.f;
float increment = 0.1f;
while(a != b)
    a+=increment;

This will result in an infinite loop.这将导致无限循环。 Is there any solutions to it, or the only way to solve this is to set a tolerance?是否有任何解决方案,或者解决此问题的唯一方法是设置容差?

Avoid using floating-point calculation when possible.尽可能避免使用浮点计算。 In this case you can treat with the numbers as integer by multiplying them by 10 and dividing by 10 in the end.在这种情况下,您可以将数字视为 integer,方法是将它们乘以 10,最后除以 10。

float a, b, increment;
int a_i = 0;
int b_i = 50;
int increment_i = 1;
while(a_i != b_i)
    a_i+=increment_i;
a = a_i / 10.f,
b = b_i / 10.f;
increment = increment_i / 10.f;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM