本文介绍了浮点比较问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 下个月,我将开始研究一个名为CAT ++的基于C ++的软件,它将在C ++中提供类似FORTRAN的数组,并将在 中使用。因此将在很大程度上依赖于 数值计算。我正在阅读29.16和29.17节的常见问题解答: http://www.parashift.com/c++-faq-lit...html#faq-29.16 作为测试,我刚在Linux,GCC 4.2.2上试过这个程序,它给了我2 不同的结果: #include< iostream> #include< string> #include< vector> int main() { const double x = 0.05; const double y = 0.07; const double z = x + y; const double key_num = x + y; if(key_num == z) { std :: cout<< " == \ n"; } else { std :: cout< < "!= \ n"; } 返回0; } ==========输出============ / home / arnuld / programs $ g ++ -ansi - 迂腐-Wall -Wextra test2.cpp / home / arnuld / programs $ ./a.out == / home / arnuld / program $ 总是输出==,现在我将key_num更改为: const double key_num = 0.12; ,这个程序现在总是输出!= / home / arnuld / programs $ g ++ -ansi -pedantic -Wall -Wextra test2.cpp / home / arnuld / programs $ ./a.out != / home / arnuld / programs $ 如常见问题解答浮动-Point是不准确的,但是我的项目非常重要,因为我正在考虑停止开发使用C ++中的软件并且仅仅使用FORTRAN来实现这个特定的 b br /> 申请特殊域名。 - http://lispmachine.wordpress.com/ 解决方案 g ++ -ansi -pedantic -Wall -Wextra test2.cpp / home / arnuld / programs ./ a.out == / home / arnuld / programs 总是输出==,现在我将key_num更改为: const double key_num = 0.12; 此程序现在总是输出!= /家庭/ arnuld /方案 Next month I will start to work on a C++ based Software named CAT++ whichis going to provide FORTRAN like arrays in C++ and will be used withinScientific Community and hence will heavily depend onNumerical-Computations. I was reading 29.16 ans 29.17 sections of FAQs: http://www.parashift.com/c++-faq-lit...html#faq-29.16as a test, I just tried this program on Linux, GCC 4.2.2 and it gave me 2different results:#include <iostream>#include <string>#include <vector>int main(){const double x = 0.05;const double y = 0.07;const double z = x + y;const double key_num = x + y;if( key_num == z ){std::cout << "==\n";}else{std::cout << "!=\n";}return 0;}========== OUTPUT ============/home/arnuld/programs $ g++ -ansi -pedantic -Wall -Wextra test2.cpp/home/arnuld/programs $ ./a.out==/home/arnuld/programs $it always outputs == , Now i changed key_num to this:const double key_num = 0.12;and this program now always outputs !=/home/arnuld/programs $ g++ -ansi -pedantic -Wall -Wextra test2.cpp/home/arnuld/programs $ ./a.out!=/home/arnuld/programs $As FAQ explains Floating-Point is inaccurate but my project is heavilyoriented towards number-crunching, so I was thinking of stop developingthat sofwtare in C++ and simply use FORTRAN for this specificapplication in a special domain.-- http://lispmachine.wordpress.com/ 解决方案 g++ -ansi -pedantic -Wall -Wextra test2.cpp/home/arnuld/programs./a.out==/home/arnuld/programsit always outputs == , Now i changed key_num to this:const double key_num = 0.12;and this program now always outputs !=/home/arnuld/programs 这篇关于浮点比较问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-15 04:28