Why?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
	cout << "static_cast<int>((12 / 10.0 - 12 / 10) * 10) = " << static_cast<int>((12 / 10.0 - 12 / 10) * 10) << endl;
	cout << "(12 / 10.0 - 12 / 10) * 10 = " << (12 / 10.0 - 12 / 10) * 10 << "\n\nWhy?\n\n";

	return 0;
}

Output:
static_cast<int>((12 / 10.0 - 12 / 10) * 10) = 1
(12 / 10.0 - 12 / 10) * 10 = 2

Why?

Press any key to continue . . .
Last edited on
Two reasons:

0.2 is not exactly representable by a computer. (yes, 2 is. but 0.2 is not.)

static_cast<> relies entirely upon the information it can get from the line of code where it is used (which isn't a lot).

Combine these, and your 0.2 gets chopped to 0.1.

What Every Computer Scientist Should Know About Floating-Point Arithmetic
http://docs.sun.com/source/806-3568/ncg_goldberg.html

Wikipedia - Floating Point
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems


You can "fix it" by being explicit about the type of data you are using.
static_cast<int>((float)(12 / 10.0 - 12 / 10) * 10)

Hope this helps.
Yes, it has helped alot! Thank you!!! :)
Topic archived. No new replies allowed.