c – 处理浮点数的精度问题
发布时间:2020-12-16 03:10:56 所属栏目:百科 来源:网络整理
导读:我想知道是否有一种克服精度问题的方法,这似乎是我机器内部浮点数表示的结果: 为了清楚起见,问题总结如下: // str is "4.600"; atof( str ) is 4.5999999999999996 double mw = atof( str ) // The variables used in the columns calculation below are:
我想知道是否有一种克服精度问题的方法,这似乎是我机器内部浮点数表示的结果:
为了清楚起见,问题总结如下: // str is "4.600"; atof( str ) is 4.5999999999999996 double mw = atof( str ) // The variables used in the columns calculation below are: // // mw = 4.5999999999999996 // p = 0.2 // g = 0.2 // h = 1 (integer) int columns = (int) ( ( mw - ( h * 11 * p ) ) / ( ( h * 11 * p ) + g ) ) + 1; 在转换为整数类型之前,列计算的结果为1.9999999999999996;所以距离2.0的预期结果还远. 任何建议最受欢迎. 解决方法
一个将浮点数转换为整数的非常简单有效的方法:
int rounded = (int)(f + 0.5); 注意:这只有在f总是为正时才有效. (谢谢j随机黑客??) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |