不被理解的毛If(x>y)z=x;x=y;y=z;和If(x>y){z=x;x=y;y=z;}的区别

Basic Tensor Functionality & Theano 1.0.0 documentation以下试题来自:
单项选择题 阅读下列FORTRAN程序: READ(*,*)X IF(X.LT.0.0)THEN Y=0.0 ELSEIF(X.GT.1.0)THEN Y=1.0 IF(X.GE.0.0)THEN Y=5.0 ENDIF ELSE Y=0.5 ENDIF WRITE(*,*)Y END 当执行上述程序时,由键盘输入则运行后的输出结果为()。
为您推荐的考试题库
你可能感兴趣的试题
A.发现源程序中的语法错误
B.改正源程序中的语法错误
C.将源程序编译成目标文件
D.将一种高级语言程序翻译成另一种高级语言程序
A.单用户单任务系统
B.单用户多任务系统
C.多用户多任务系统
D.多用户单任务系统
A.P=X+Y.GE.X*X.AND.X+1.LT.Y+2
B.Q=X*X+Y*Y.GT.10.0.OR.X.LE.Y
C.P=(X.OR.Y).EQ.0.0
D.Q=X*Y.GT.0.0.NEQV.P.AND.Q
热门相关试卷
最新相关试卷int x=0, y=1, z=2,if (x++){w =}else if (x++ && y &= 1){w =}else if (x++ && z & 1){w =}_百度知道
int x=0, y=1, z=2,if (x++){w =}else if (x++ && y &= 1){w =}else if (x++ && z & 1){w =}
if (x++){w =}else if (x++ && y &= 1){w =}else if (x++ && z & 1){w =}执行了以下程序段后xint x=0, y=1, z=2, w
我有更好的答案
但条件不满足,x+=1 x=1{w =/w=1}else if (x++ && z & 1)//}else if (x++ && y &= 1)//x=1 y&=1 条件满足,然后x+=1 x=2{w =/不执行{w = zif (x++)//执行
为什么最后一步不执行呢?谢谢!!!
if else,依次判断,只要之前的条件满足了,之后的都不会执行,这也是计算机节省运行时间的一种方式
采纳率:56%
( 首先if语句中的x++ 是0 不成立,所以执行第二项else if 这时的x++s 是1 成立然后 与 也成立 执行w=然后跳出 结果就是x=2,w=1.
——那个x++是先用后加,也就是说x是0, x++是0,然后x才是1,这点要明白)
但答案是:x = 2, w = 1;
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。Checking if a double (or float) is NaN in C++ - Stack Overflow
Join Stack Overflow to learn, share knowledge, and build your career.
or sign in with
Is there an isnan() function?
PS.: I'm in
(if that makes a difference).
I had this solved by using isnan() from &math.h&, which doesn't exist in &cmath&, which I was #includeing at first.
12.1k1781107
74.7k56157205
According to the IEEE standard, NaN values have the odd property that comparisons involving them are always false. That is, for a float f, f != f will be true only if f is NaN.
Note that, as some comments below have pointed out, not all compilers respect this when optimizing code.
For any compiler which claims to use IEEE floating point, this trick should work. But I can't guarantee that it will work in practice. Check with your compiler, if in doubt.
198k39282511
There is no isnan() function available in current C++ Standard Library. It was introduced in
and defined as a
not a function. Elements of standard library defined by C99 are not part of current C++ standard ISO/IEC
neither its update ISO/IEC .
In 2005 Technical Report 1 was proposed. The TR1 brings compatibility with C99 to C++. In spite of the fact it has never been officially adopted to become C++ standard, many ( or
C++ implementations do provide TR1 features, all of them or only some (Visual C++ 9.0 does not provide C99 math functions).
If TR1 is available, then cmath includes C99 elements like isnan(), isfinite(), etc. but they are defined as functions, not macros, usually in std::tr1:: namespace, though many implementations (i.e. GCC 4+ on Linux or in XCode on Mac OS X 10.5+) inject them directly to std::, so std::isnan is well defined.
Moreover, some implementations of C++ still make C99 isnan() macro available for C++ (included through cmath or math.h), what may cause more confusions and developers may assume it's a standard behaviour.
A note about Viusal C++, as mentioned above, it does not provide std::isnan neither std::tr1::isnan, but it provides an extension function defined as _isnan() which has been available since
On XCode, there is even more fun. As mentioned, GCC 4+ defines std::isnan. For older versions of compiler and library form XCode, it seems (here is ), haven't had chance to check myself) two functions are defined, __inline_isnand() on Intel and __isnand() on Power PC.
25.7k87391
First solution: if you are using C++11
Since this was asked there were a bit of new developments: it is important to know that std::isnan() is part of C++11
Defined in header &cmath&
bool isnan( float arg ); (since C++11)
bool isnan( double arg ); (since C++11)
bool isnan( long double arg ); (since C++11)
Determines if the given floating point number arg is not-a-number (NaN).
Parameters
arg: floating point value
Return value
true if arg is NaN, false otherwise
Please note that this is incompatible with -fast-math if you use g++, see below for other suggestions.
Other solutions: if you using non C++11 compliant tools
For C99, in C, this is implemented as a macro isnan(c)that returns an int value. The type of x shall be float, double or long double.
Various vendors may or may not include or not a function isnan().
The supposedly portable way to check for NaN is to use the IEEE 754 property that NaN is not equal to itself: i.e. x == x will be false for x being NaN.
However the last option may not work with every compiler and some settings (particularly optimisation settings), so in last resort, you can always check the bit pattern ...
4,49543157
There is also a
present in Boost that have neat tools to deal with floating point datatypes
#include &boost/math/special_functions/fpclassify.hpp&
You get the following functions:
template &class T& bool isfinite(T z);
template &class T& bool isinf(T t);
template &class T& bool isnan(T t);
template &class T& bool isnormal(T t);
If you have time then have a look at whole Math toolkit from Boost, it has many useful tools and is growing quickly.
Also when dealing with floating and non-floating points it might be a good idea to look at the .
14.7k22956
There are three "official" ways: posix isnan macro, c++0x isnan function template, or visual c++ _isnan function.
Unfortunately it's rather impractical to detect which of those to use.
And unfortunately, there's no reliable way to detect whether you have IEEE 754 representation with NaNs. The standard library offers an official such way (numeric_limits&double&::is_iec559). But in practice compilers such as g++ screw that up.
In theory one could use simply x != x, but compilers such as g++ and visual c++ screw that up.
So in the end, test for the specific NaN bitpatterns, assuming (and hopefully enforcing, at some point!) a particular representation such as IEEE 754.
EDIT: as an example of "compilers such as g++ & screw that up", consider
#include &limits&
#include &assert.h&
void foo( double a, double b )
assert( a != b );
int main()
typedef std::numeric_limits&double& I
double const nan1 = Info::quiet_NaN();
double const nan2 = Info::quiet_NaN();
foo( nan1, nan2 );
Compiling with g++ (TDM-2 mingw32) 4.4.1:
C:\test& type "C:\Program Files\@commands\gnuc.bat"
@rem -finput-charset=windows-1252
@g++ -O -pedantic -std=c++98 -Wall -Wwrite-strings %* -Wno-long-long
C:\test& gnuc x.cpp
C:\test& a && echo works... || echo !failed
C:\test& gnuc x.cpp --fast-math
C:\test& a && echo works... || echo !failed
Assertion failed: a != b, file x.cpp, line 6
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
C:\test& _
116k9139247
There is an std::isnan if you compiler supports c99 extensions, but I'm not sure if mingw does.
Here is a small function which should work if your compiler doesn't have the standard function:
bool custom_isnan(double var)
volatile double d =
return d !=
11.1k53035
You can use numeric_limits&float&::quiet_NaN( ) defined in the limits standard library to test with.
There's a separate constant defined for double.
#include &iostream&
#include &math.h&
#include &limits&
int main( )
cout && "The quiet NaN for type float is:
&& numeric_limits&float&::quiet_NaN( )
float f_nan = numeric_limits&float&::quiet_NaN();
if( isnan(f_nan) )
cout && "Float was Not a Number: " && f_nan &&
I don't know if this works on all platforms, as I only tested with g++ on Linux.
267k151482776
You can use the isnan() function, but you need to include the C math library.
#include &cmath&
As this function is part of C99, it is not available everywhere. If your vendor does not supply the function, you can also define your own variant for compatibility.
#ifndef isnan
inline bool isnan(double x) {
return x !=
nan prevention
My answer to this question is don't use retroactive checks for nan.
Use preventive checks for divisions of the form 0.0/0.0 instead.
#include &float.h&
float x=0.
// I'm gonna divide by x!
// Wait! Let me check if x is 0
x = FLT_MIN ;
// oh, since x was 0, i'll just make it really small instead.
float y = 0.f /
// whew, `nan` didn't appear.
nan results from the operation 0.f/0.f, or 0.0/0.0.
nan is a terrible nemesis to the stability of your code that must be detected and prevented very carefully1.
The properties of nan that are different from normal numbers:
nan is toxic, (5*nan=nan)
nan is not equal to anything, not even itself (nan != nan)
nan not greater than anything (nan !> 0)
nan is not less than anything (nan !& 0)
The last 2 properties listed are counter-logical and will result in odd behavior of code that relies on comparisons with a nan number (the 3rd last property is odd too but you're probably not ever going to see x != x ? in your code (unless you are checking for nan (unreliably))).
In my own code, I noticed that nan values tend to produce difficult to find bugs. (Note how this is not the case for inf or -inf.
(-inf & 0) returns TRUE, ( 0 & inf ) returns TRUE, and even (-inf & inf) returns TRUE. So, in my experience, the behavior of the code is often still as desired).
what to do under nan
What you want to happen under 0.0/0.0 must be handled as a special case, but what you do must depend on the numbers you expect to come out of the code.
In the example above, the result of (0.f/FLT_MIN) will be 0, basically.
You may want 0.0/0.0 to generate HUGE instead.
float x=0.f, y=0.f,
if( !x && !y )
// 0.f/0.f case
z = FLT_MAX ;
// biggest float possible
// regular division.
So in the above, if x were 0.f, inf would result (which has pretty good/nondestructive behavior as mentioned above actually).
Remember, .
So you must always check for integer division by 0.
Just because 0.0/0.0 quietly evaluates to nan doesn't mean you can be lazy and not check for 0.0/0.0 before it happens.
1 Checks for nan via x != x are sometimes unreliable (x != x being stripped out by some optimizing compilers that break IEEE compliance, specifically when the -ffast-math switch is enabled).
32.5k40202287
The following code uses the definition of NAN (all exponent bits set, at least one fractional bit set) and assumes that sizeof(int) = sizeof(float) = 4.
You can look up NAN in Wikipedia for the details.
bool IsNan( float value )
return ((*(UINT*)&value) & 0x7fffffff) & 0x7f800000;
inline bool IsNan(float f)
const uint32 u = *(uint32*)&f;
return (u&0x7F800000) == 0x7F800000 && (u&0x7FFFFF);
// Both NaN and qNan.
inline bool IsNan(double d)
const uint64 u = *(uint64*)&d;
return (u&0x7FF0ULL) == 0x7FF0ULL && (u&0xFFFFFFFFFFFFFULL);
This works if sizeof(int) is 4 and sizeof(long long) is 8.
During run time it is only comparison, castings do not take any time. It just changes comparison flags configuration to check equality.
10.5k1869115
5,40414380
As of C++14 there are a number of ways to test if a floating point number value is a NaN.
Of these ways, only checking of the bits of the number's representation,
works reliably, as noted in my original answer. In particular, std::isnan and the often proposed check v != v, do not work reliably and should not be used, lest your code stops working correctly when someone decides that floating point optimization is needed, and asks the compiler to do that. This situation can change, compilers can get more conforming, but for this issue that hasn't happened in the 6 years since the original answer.
For about 6 years my original answer was the selected solution for this question, which was OK. But recently a highly upvoted answer recommending the unreliable v != v test has been selected. Hence this additional more up-to-date answer (we now have the C++11 and C++14 standards, and C++17 on the horizon).
The main ways to check for NaN-ness, as of C++14, are:
std::isnan(value) )
is the intended standard library way since C++11. isnan apparently conflicts with the
Posix macro of the same name, but in practice that isn't a problem. The main problem is
that when floating point arithmetic optimization is requested, then with at least one main compiler, namely g++, std::isnan returns false for NaN argument.
(fpclassify(value) == FP_NAN) )
Suffers from the same problem as std::isnan, i.e., is not reliable.
(value != value) )
Recommended in many SO answers. Suffers from the same problem as std::isnan, i.e.,
is not reliable.
(value == Fp_info::quiet_NaN()) )
This is a test that with standard behavior should not detect NaNs, but that with the
optimized behavior maybe could detect NaNs (due to optimized code just comparing the
bitlevel representations directly), and perhaps combined with another way to
cover the standard un-optimized behavior, could reliably detect NaN. Unfortunately
it turned out to not work reliably.
(ilogb(value) == FP_ILOGBNAN) )
Suffers from the same problem as std::isnan, i.e., is not reliable.
isunordered(1.2345, value) )
Suffers from the same problem as std::isnan, i.e., is not reliable.
is_ieee754_nan( value ) )
This isn't a standard function. It's checking of the bits according to the IEEE 754
standard. It's completely reliable but the code is somewhat system-dependent.
In the following complete test code &success& is whether an expression reports Nan-ness of the value. For most expressions this measure of success, the goal of detecting NaNs and only NaNs, corresponds to their standard semantics. For the (value == Fp_info::quiet_NaN()) ) expression, however, the standard behavior is that it doesn't work as a NaN-detector.
#include &cmath&
// std::isnan, std::fpclassify
#include &iostream&
#include &iomanip&
// std::setw
#include &limits&
#include &limits.h&
// CHAR_BIT
#include &sstream&
#include &stdint.h&
// uint64_t
#define TEST( x, expr, expected ) \
const auto value = \
const bool result = \
stream && boolalpha && #x " = " && x && ", (" #expr ") = " && \
&& setw( 60 ) && stream.str() && "
&& (result == expected? "Success" : "FAILED") \
#define TEST_ALL_VARIABLES( expression ) \
TEST( v, expression, true ); \
TEST( u, expression, false ); \
TEST( w, expression, false )
using Fp_info = numeric_limits&double&;
inline auto is_ieee754_nan( double const x )
static constexpr bool
is_claimed_ieee754
= Fp_info::is_iec559;
static constexpr int
n_bits_per_byte
= CHAR_BIT;
using Byte =
static_assert( is_claimed_ieee754, "!" );
static_assert( n_bits_per_byte == 8, "!" );
static_assert( sizeof( x ) == sizeof( uint64_t ), "!" );
#ifdef _MSC_VER
uint64_t const bits = reinterpret_cast&uint64_t const&&( x );
Byte bytes[sizeof(x)];
memcpy( bytes, &x, sizeof( x ) );
uint64_t int_
memcpy( &int_value, bytes, sizeof( x ) );
uint64_t const& bits = int_
static constexpr uint64_t
static constexpr uint64_t
static constexpr uint64_t
mantissa_mask
= 0x000FFFFFFFFFFFFF;
(void) sign_
return (bits & exp_mask) == exp_mask and (bits & mantissa_mask) != 0;
auto main()
double const v = Fp_info::quiet_NaN();
double const u = 3.14;
double const w = Fp_info::infinity();
cout && boolalpha &&
cout && "Compiler claims IEEE 754 = " && Fp_info::is_iec559 &&
TEST_ALL_VARIABLES( std::isnan(value) );
TEST_ALL_VARIABLES( (fpclassify(value) == FP_NAN) );
TEST_ALL_VARIABLES( (value != value) );
TEST_ALL_VARIABLES( (value == Fp_info::quiet_NaN()) );
TEST_ALL_VARIABLES( (ilogb(value) == FP_ILOGBNAN) );
TEST_ALL_VARIABLES( isunordered(1.2345, value) );
TEST_ALL_VARIABLES( is_ieee754_nan( value ) );
Results with g++ (note again that the standard behavior of (value == Fp_info::quiet_NaN()) is that it doesn't work as a NaN-detector, it's just very much of practical interest here):
[C:\my\forums\so\282
(detect NaN)]
& g++ --version | find "++"
g++ (x86_64-win32-sjlj-rev1, Built by MinGW-W64 project) 6.3.0
[C:\my\forums\so\282
(detect NaN)]
& g++ foo.cpp && a
Compiler claims IEEE 754 = true
v = nan, (std::isnan(value)) = true
u = 3.14, (std::isnan(value)) = false
w = inf, (std::isnan(value)) = false
v = nan, ((fpclassify(value) == 0x0100)) = true
u = 3.14, ((fpclassify(value) == 0x0100)) = false
w = inf, ((fpclassify(value) == 0x0100)) = false
v = nan, ((value != value)) = true
u = 3.14, ((value != value)) = false
w = inf, ((value != value)) = false
v = nan, ((value == Fp_info::quiet_NaN())) = false
u = 3.14, ((value == Fp_info::quiet_NaN())) = false
w = inf, ((value == Fp_info::quiet_NaN())) = false
v = nan, ((ilogb(value) == ((int)0x))) = true
u = 3.14, ((ilogb(value) == ((int)0x))) = false
w = inf, ((ilogb(value) == ((int)0x))) = false
v = nan, (isunordered(1.2345, value)) = true
u = 3.14, (isunordered(1.2345, value)) = false
w = inf, (isunordered(1.2345, value)) = false
v = nan, (is_ieee754_nan( value )) = true
u = 3.14, (is_ieee754_nan( value )) = false
w = inf, (is_ieee754_nan( value )) = false
[C:\my\forums\so\282
(detect NaN)]
& g++ foo.cpp -ffast-math && a
Compiler claims IEEE 754 = true
v = nan, (std::isnan(value)) = false
u = 3.14, (std::isnan(value)) = false
w = inf, (std::isnan(value)) = false
v = nan, ((fpclassify(value) == 0x0100)) = false
u = 3.14, ((fpclassify(value) == 0x0100)) = false
w = inf, ((fpclassify(value) == 0x0100)) = false
v = nan, ((value != value)) = false
u = 3.14, ((value != value)) = false
w = inf, ((value != value)) = false
v = nan, ((value == Fp_info::quiet_NaN())) = true
u = 3.14, ((value == Fp_info::quiet_NaN())) = true
w = inf, ((value == Fp_info::quiet_NaN())) = true
v = nan, ((ilogb(value) == ((int)0x))) = true
u = 3.14, ((ilogb(value) == ((int)0x))) = false
w = inf, ((ilogb(value) == ((int)0x))) = false
v = nan, (isunordered(1.2345, value)) = false
u = 3.14, (isunordered(1.2345, value)) = false
w = inf, (isunordered(1.2345, value)) = false
v = nan, (is_ieee754_nan( value )) = true
u = 3.14, (is_ieee754_nan( value )) = false
w = inf, (is_ieee754_nan( value )) = false
[C:\my\forums\so\282
(detect NaN)]
Results with Visual C++:
[C:\my\forums\so\282
(detect NaN)]
& cl /nologo- 2&&1 | find "++"
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23725 for x86
[C:\my\forums\so\282
(detect NaN)]
& cl foo.cpp /Feb && b
Compiler claims IEEE 754 = true
v = nan, (std::isnan(value)) = true
u = 3.14, (std::isnan(value)) = false
w = inf, (std::isnan(value)) = false
v = nan, ((fpclassify(value) == 2)) = true
u = 3.14, ((fpclassify(value) == 2)) = false
w = inf, ((fpclassify(value) == 2)) = false
v = nan, ((value != value)) = true
u = 3.14, ((value != value)) = false
w = inf, ((value != value)) = false
v = nan, ((value == Fp_info::quiet_NaN())) = false
u = 3.14, ((value == Fp_info::quiet_NaN())) = false
w = inf, ((value == Fp_info::quiet_NaN())) = false
v = nan, ((ilogb(value) == 0x7fffffff)) = true
u = 3.14, ((ilogb(value) == 0x7fffffff)) = false
w = inf, ((ilogb(value) == 0x7fffffff)) = true
v = nan, (isunordered(1.2345, value)) = true
u = 3.14, (isunordered(1.2345, value)) = false
w = inf, (isunordered(1.2345, value)) = false
v = nan, (is_ieee754_nan( value )) = true
u = 3.14, (is_ieee754_nan( value )) = false
w = inf, (is_ieee754_nan( value )) = false
[C:\my\forums\so\282
(detect NaN)]
& cl foo.cpp /Feb /fp:fast && b
Compiler claims IEEE 754 = true
v = nan, (std::isnan(value)) = true
u = 3.14, (std::isnan(value)) = false
w = inf, (std::isnan(value)) = false
v = nan, ((fpclassify(value) == 2)) = true
u = 3.14, ((fpclassify(value) == 2)) = false
w = inf, ((fpclassify(value) == 2)) = false
v = nan, ((value != value)) = true
u = 3.14, ((value != value)) = false
w = inf, ((value != value)) = false
v = nan, ((value == Fp_info::quiet_NaN())) = false
u = 3.14, ((value == Fp_info::quiet_NaN())) = false
w = inf, ((value == Fp_info::quiet_NaN())) = false
v = nan, ((ilogb(value) == 0x7fffffff)) = true
u = 3.14, ((ilogb(value) == 0x7fffffff)) = false
w = inf, ((ilogb(value) == 0x7fffffff)) = true
v = nan, (isunordered(1.2345, value)) = true
u = 3.14, (isunordered(1.2345, value)) = false
w = inf, (isunordered(1.2345, value)) = false
v = nan, (is_ieee754_nan( value )) = true
u = 3.14, (is_ieee754_nan( value )) = false
w = inf, (is_ieee754_nan( value )) = false
[C:\my\forums\so\282
(detect NaN)]
Summing up the above results, only direct testing of the bit-level representation, using the is_ieee754_nan function defined in this test program, worked reliably in all cases with both g++ and Visual C++.
After posting the above I became aware of yet another possible to test for NaN, mentioned in
here, namely ((value & 0) == (value &= 0)). That turned out to work fine with Visual C++ but failed with g++'s -ffast-math option. Only direct bitpattern testing works reliably.
116k9139247
A possible solution that would not depend on the specific IEEE representation for NaN used would be the following:
template&class T&
bool isnan( T f ) {
(T)0.0/(T)0.0;
return 0 == memcmp( (void*)&f, (void*)&_nan, sizeof(T) );
As for me the solution could be a macro to make it explicitly inline and thus fast enough.
It also works for any float type. It bases on the fact that the only case when a value is not equals itself is when the value is not a number.
#ifndef isnan
#define isnan(a) (a != a)
After reading the other answers I wanted something that would pass through the floating-point comparison warning and would not break under fast math. The following code appears to work:
Portable warning-free NaN test:
* Does not emit warning with -Wfloat-equal (does not use float comparisons)
* Works with -O3 -ffast-math (floating-point optimization)
* Only call to standard library is memset and memcmp via &cstring&
* Works for IEEE 754 compliant floating-point representations
* Also works for extended precision long double
#include &cstring&
template &class T& bool isNaN(T x)
/*Initialize all bits including those used for alignment to zero. This sets
all the values to positive zero but does not clue fast math optimizations as
to the value of the variables.*/
memset(z, 0, sizeof(z));
z[1] = -z[0];
z[3] = z[0] / z[2];
/*Rationale for following test:
* x is 0 or -0
--& z[2] = 0, z[3] = NaN
* x is a negative or positive number
--& z[3] = 0
* x is a negative or positive denormal number --& z[3] = 0
* x is negative or positive infinity
--& z[3] = 0
(IEEE 754 guarantees that 0 / inf is zero)
* x is a NaN
--& z[3] = NaN != 0.
//Do a bitwise comparison test for positive and negative zero.
bool z2IsZero = memcmp(&z[2], &z[0], sizeof(T)) == 0 ||
memcmp(&z[2], &z[1], sizeof(T)) == 0;
bool z3IsZero = memcmp(&z[3], &z[0], sizeof(T)) == 0 ||
memcmp(&z[3], &z[1], sizeof(T)) == 0;
//If the input is bitwise zero or negative zero, then it is not NaN.
return !z2IsZero && !z3IsZ
//NaN test suite
#include &iostream&
/*If printNaN is true then only expressions that are detected as NaN print and
vice versa.*/
template &class T& void test(bool printNaN)
T v[10] = {-0.0, 0.0, -1.0, 1.0,
std::numeric_limits&T&::infinity(),
-std::numeric_limits&T&::infinity(),
std::numeric_limits&T&::denorm_min(),
-std::numeric_limits&T&::denorm_min(),
std::numeric_limits&T&::quiet_NaN(),
std::numeric_limits&T&::signaling_NaN()};
for(int i = 0; i & 10; i++)
for(int j = 0; j & 10; j++)
if(isNaN(v[i] + v[j]) == printNaN)
std::cout && v[i] && "+" && v[j] && " = " && v[i] + v[j] && std::
if(isNaN(v[i] - v[j]) == printNaN)
std::cout && v[i] && "-" && v[j] && " = " && v[i] - v[j] && std::
if(isNaN(v[i] * v[j]) == printNaN)
std::cout && v[i] && "*" && v[j] && " = " && v[i] * v[j] && std::
if(isNaN(v[i] / v[j]) == printNaN)
std::cout && v[i] && "/" && v[j] && " = " && v[i] / v[j] && std::
//Test each floating-point type.
int main()
std::cout && "NaNs:" && std::
test&float&(true);
test&double&(true);
test&long double&(true);
std::cout && std::endl && "Not NaNs:" && std::
test&float&(false);
test&double&(false);
test&long double&(false);
Considering that (x != x) is not always guaranteed for NaN (such as if using the -ffast-math option), I've been using:
#define IS_NAN(x) (((x) & 0) == ((x) &= 0))
Numbers can't be both & 0 and >= 0, so really this check only passes if the number is neither less than, nor greater than or equal to zero.
Which is basically no number at all, or NaN.
You could also use this if you prefer:
#define IS_NAN(x) (!((x)&0) && !((x)&=0)
I'm not sure how this is affected by -ffast-math though, so your mileage may vary.
This works:
#include &iostream&
#include &math.h&
int main ()
char ch='a';
double val = nan(&ch);
if(isnan(val))
cout && "isnan" &&
output: isnan
The IEEE standard says
when exponent is all 1s
mantissa is not zero,
the number is a NaN.
Double is 1 sign bit, 11 exponent bits and 52 mantissa bits.
Do a bit check.
It seems to me that the best truly cross-platform approach would be to use a union and to test the bit pattern of the double to check for NaNs.
I have not thoroughly tested this solution, and there may be a more efficient way of working with the bit patterns, but I think that it should work.
#include &stdint.h&
#include &stdio.h&
int main()
//Test if a double is NaN
double d = 0.0 / 0.0;
if((n.bits | 0x800FFFFFFFFFFFFF) == 0xFFFFFFFFFFFFFFFF)
printf("NaN: %f", d);
As comments above state a != a will not work in g++ and some other compilers, but this trick should. It may not be as efficient, but it's still a way:
bool IsNan(float a)
char s[4];
sprintf(s, "%.3f", a);
if (s[0]=='n')
Basically, in g++ (I am not sure about others though) printf prints 'nan' on %d or %.f formats if variable is not a valid integer/float. Therefore this code is checking for the first character of string to be 'n' (as in "nan")
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Upcoming Events
ends Mar 27
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 不被理解的毛 的文章

 

随机推荐