double-precison
I wont to store in a variable a real number,for example 0.132547698,but the double can store just 6 digits.Take a look:
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
using namespace std;
int main() {
double a,b,c;
a=1.0/3.0;
b=1.23456789;
c=1234.56789;
cout<<a<<endl<<b<<endl<<c;
cin.ignore();
return 0;
}
|
the output:
1 2 3
|
0.333333
1.23457
1234.57
|
What should I do ? I've seen on other topics that the double data type is much larger...
Thanks :)
The double is capable of storing up to 15 decimal places, and does so in your code. The problem is 'cout' truncates it to a certain precision.
1 2 3 4 5 6 7 8 9
|
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a = (1.0/3.0);
cout << setprecision(15) << a << endl;
}
|
you can read about setprecision here:
http://cplusplus.com/reference/iomanip/setprecision/
That will allow you to change the decimal precision of 'cout'.
Just because you don't see the extra digits displayed, it doesn't mean they don't exist.
1 2 3 4 5 6 7 8
|
double a,b,c;
a = 1.0/3.0;
b = 0.333333;
c = a - b;
cout << "a: " << a << endl;
cout << "b: " << b << endl;
cout << "c: " << c << endl;
|
Output:
a: 0.333333
b: 0.333333
c: 3.33333e-007 |
Notice that c is not zero.
Topic archived. No new replies allowed.