问题描述
编译:
g ++ crash.cpp -O2
崩溃:
g ++(Gentoo 4.3.2 p1 .1)4.3.2
g ++(GCC)4.3.0 20080428(Red Hat 4.3.0-8)
g ++(ubuntu当前稳定版)
重现的步骤:
1.制作文件crash.cpp(下面的内容)
2. g ++ crash.cpp -O2
3. ./a.out
浮点异常
资料来源:
#包括< iostream>
#include< fenv.h>
float g(const float& x)
{
float y = x;
if(y == 0.0f)
{
y = 1.0f;
}
返回x / y;
}
void f(const float& z)
{
if(z 0.0f)
{
float Unit2 = g(z);
std :: cout<<第2单元;
}
}
int main()
{
feenableexcept(FE_INVALID);
浮动a = 130.0f;
f(a);
返回0;
}
Compile with:
g++ crash.cpp -O2
Crashes on:
g++ (Gentoo 4.3.2 p1.1) 4.3.2
g++ (GCC) 4.3.0 20080428 (Red Hat 4.3.0-8)
g++ (ubuntu current stable)
Steps to reproduce:
1. Make a file crash.cpp (contents below)
2. g++ crash.cpp -O2
3. ./a.out
Floating point exception
Source:
#include <iostream>
#include <fenv.h>
float g(const float& x)
{
float y = x;
if(y == 0.0f)
{
y=1.0f;
}
return x/y;
}
void f(const float &z)
{
if (z 0.0f)
{
float Unit2 = g(z);
std::cout << Unit2;
}
}
int main()
{
feenableexcept(FE_INVALID);
float a = 130.0f;
f(a);
return 0;
}
推荐答案
这里不会崩溃:
g ++(Ubuntu 4.3.2-1ubuntu11)4.3.2
Doesn''t crash here with:
g++ (Ubuntu 4.3.2-1ubuntu11) 4.3.2
这里打印''1',这是什么一世本来应该的。
It prints ''1'' here, which is what I would have expected.
从不比较2个浮点数是否相等。
除了它是一个cpu的密集操作之外,
以下是预期的......
#include< iostream>
int main()
{
float fa(0.0f);
float fb(0.0f);
if(fa == fb)
std :: cout<< not equal\\\
;
else
std :: cout<< " equal\\\
";
std :: cout<< 按ENTER键进入EXIT.\ n;
std :: cin.get();
}
/ *
不等于
* /
Never compare 2 floats for equality.
Apart from the fact that its an intensive operation for a cpu,
the following is expected...
#include <iostream>
int main()
{
float fa(0.0f);
float fb(0.0f);
if( fa == fb)
std::cout << "not equal\n";
else
std::cout << "equal\n";
std::cout << "Press ENTER to EXIT.\n";
std::cin.get();
}
/*
not equal
*/
z可能是0.0000000001f
z might be 0.0000000001f
永远不要比较2个浮点数是否相等。
Never compare 2 floats for equality.
似乎是避免除以零的好方法。
Seems like a pretty good way to avoid dividing by zero.
嗯,没有。这几乎是微不足道的。
Um, no. It''s nearly trivial.
符合标准的C ++编译器不会产生该结果。
值都是准确的,比较准确。
-
Pete
Roundhouse Consulting,Ltd。()The brbsp的作者>
标准C ++库扩展:教程和参考
()
A standarde-conforming C++ compiler will not produce that result. Both
values are exact, and the comparison is exact.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
这篇关于代码在运行时崩溃 - 这是有效的c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!