Why doesn't it print the full decimal number?
#include<iostream>
using namespace std;
int main (void)
{
int test,r,i=0;
float f;
cin>>test;
i++;
while ( test!=0 )
{
cin>>r;
f = 4*r*r + 0.25;
cout<<"Case "<<i<<":"<<" "<<f<<"\n";
i++;
test--;
}
return 0;
}
I made this simple program that evaluates the value of an expression 4*r*r+0.25
. It r
will always be an integer from 1 <= r <= 1000000 here. I have to print the value of the above expression to two decimal places. However, when I enter r
anything -> 50 values , it only shows the result as output.2
, that is, for example, when entering a value as 50
, it shows the result as 10000.2
. Why is this happening? I tried using double and not float but it didn't help.
source to share
By default, floating point values โโare printed with six significant digits. You can use a manipulator setprecision
to specify more precision:
#include <iomanip>
std::cout << std::setprecision(10); // specify up to 10 significant figures
There are two more problems you will run into for large values:
- the computation
4*r*r
uses integer arithmetic and will overflow if the integer type is not large enough. You can useint64_t
either floating point type to support input values โโup to 1,000,000. -
float
can only contain up to seven decimal digits and so you still lose precision for valuesr
over a few thousand.double
should be sufficient for input values โโup to 1,000,000.
source to share
Let's take a look at some simplified code:
#include <iostream>
#include <iomanip>
int main (void) {
std::cout << 10000.25 << "\n";
std::cout << std::setprecision(20);
std::cout << 10000.25 << "\n";
}
Output:
10000.2
10000.25
If you'd like to see this in action, I've included an example of this at ideone.com .
source to share