problem here

#include <iostream>
using namespace std;
int main() {
double a = 0.1, b = 0.3;
double res = ((a + a + a - b) * 1e17) / ((b – a – a - a) * 1e17);
cout << res << endl; // Why?
}

result is -1 why
please help
No, problem is there.:)

The problem is that 0.1 + 0.1 + 0.1 < 0.3 because float numbers can not exactly represent 0.1.

EDIT:

Only I was mistaken. Shall be

0.1 + 0.1 + 0.1 > 0.3

The result of execution the statements

1
2
std::cout << std::setprecision( 17 ) << 0.1 << std::endl;
std::cout << std::setprecision( 17 ) << 0.3 << std::endl;


is

0.10000000000000001
0.29999999999999999


Even more visible

1
2
3
4
std::cout << std::setprecision( 17 ) << 0.1 << std::endl;
std::cout << std::setprecision( 17 ) << 0.1 + 0.1 << std::endl;
std::cout << std::setprecision( 17 ) << 0.1 + 0.1 + 0.1 << std::endl;
std::cout << std::setprecision( 17 ) << 0.3 << std::endl;


0.10000000000000001
0.20000000000000001
0.30000000000000004
0.29999999999999999
Last edited on
Topic archived. No new replies allowed.