How get -nan on C++ 14?

I need to get -nan used only double type and arithmetics.

So, the code should be like that:

double a = ...

cout << a << endl;

-nan

where ... is some expression.

Upvotes: 3

Views: 818

Answers (3)

Malcolm McLean
Malcolm McLean

Reputation: 6404

To get a negative nan, simply OR a NaN representation with 0x80000000. You'll have to play about with casting the address to an unsigned char * or long long *, or course.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234695

If your platform uses IEEE754 floating point then 0.0 / 0.0 will evaluate to NaN.

Alternatively you can use std::numeric_limits<double>::quiet_NaN(), having checked that std::numeric_limits<double>::has_quiet_NaN is true on your platform.

Really there is no such thing as a signed NaN, although a representation of NaN might contain a sign bit which could be picked up by the std::cout. Perhaps on your platform -0.0 / 0.0 generates a "negative" NaN. The result of cout << a for the case where a is NaN is entirely compiler-dependent.

Upvotes: 2

Paul R
Paul R

Reputation: 212969

You can just use std::nan, e.g.

#include <iostream>
#include <cmath>

int main()
{
    double a = -std::nan("1");

    std::cout << a << std::endl;
}

LIVE DEMO

Upvotes: 5

Related Questions