I've read that double stores integer and non-integer values. Is that completely true or is there something more to it? |
A double contains 64 bits divided into two parts, a mantissa and an exponent. The mantissa is like a scientific notation part and the exponent is an exponent. This is different from an integer where a number is represented purely by a single binary value. Now, something to consider is that a number like 0.1 in decimal (base 10) is a repeating number in binary (0.0001100110011...). This means that there WILL be rounding errors.
In short, the following is NOT safe because it may not be EXACTLEY true due to potential rounding errors.
|
for (double i = 0; i != 1000000000; i+=0.1) something();
|
The for loop may not exit because i may not be EXACTLEY 1000000000.
Now for your other issue:
For any numbers representing a real value, doubles are perfectly reasonable. Use integers for increments or numbers that WILL NOT have a remainder. So double is okay. Note that the 64 bits that make a double do not contain any operation on formatting. The cout itself is what controls that. If you want to see 40000000 instead of 4e+007, then you'll need to use iomanipulators.
cout << "The result is: " << fixed << x << endl;
The "
fixed" manipulator forces non-scientific notation.
One further issue: Lines 12 and 19 should be
if (t==1)
not
[if (t=1)