user10235414
user10235414

Reputation:

Unknown behavior of Round function in C++

#include <iostream>

int main()
{
    double number1 = 1.4999999999999999;
    double number2 = 1.499999999999999;

std::cout << "NUMBER 1 => ROUND (" << number1 << ") = " << round(number1) << std::endl;
std::cout << "NUMBER 2 => ROUND (" << number2 << ") = " << round(number2) << std::endl;

std::cin.get();
}

Output for above code is as follows: -

NUMBER 1 => ROUND (1.5) = 2

NUMBER 2 => ROUND (1.5) = 1

I am unclear how my number1 and number2 are changing to 1.5 and if so they're changing to 1.5 then why two different output's of round function for same number.

Tried using long double still same output

I am using Visual Studio 2019, will that make any difference?

Upvotes: 0

Views: 141

Answers (2)

Marshall Clow
Marshall Clow

Reputation: 16690

On a machine using IEEE-754 floating point representation (i.e, most of the machines today). number1 is exactly the same as 1.5.

You can inspect the bit patterns using std::hexfloat:

#include <iostream>
#include <iomanip>

int main()
{
    double number1 = 1.4999999999999999;
    double number2 = 1.499999999999999;

    std::cout << std::hexfloat << number1 << " " << number2 << std::endl;
}

prints 0x1.8p+0 0x1.7fffffffffffbp+0

Upvotes: 2

dxiv
dxiv

Reputation: 17668

#include <iostream>

int main()
{
    double number0 = 1.5;
    double number1 = 1.4999999999999999;
    double number2 = 1.499999999999999;
 
    std::cout << (number1 == number0) << " " << (number2 < number0) << std::endl;
}

The above outputs 1 1 on platforms that use IEEE-754 for representing floating points. In this case, number1 is stored as exactly 1.5 and gets rounded up to 2 while number2 has a value strictly less than 1.5 and gets rounded down to 1.

Upvotes: 4

Related Questions