Pls suggest the code so that the value 9.8754321 is exactly displayed without any truncation? Dont use manipulator or printf function. It is expected to use only formatting flags.
Code:
int main()
{
float i=9.8754321 ;
cout<<i;
}
Printable View
Pls suggest the code so that the value 9.8754321 is exactly displayed without any truncation? Dont use manipulator or printf function. It is expected to use only formatting flags.
Code:
int main()
{
float i=9.8754321 ;
cout<<i;
}
setprecision is a manipulator and hence this is not the required solution.
Then use the precision member function. That said, printing a floating point value exactly does not sound right, unless that value is exactly represented in floating point.Quote:
Originally Posted by forumuser
I don't think this can be done with format flags alone.
You could print the integral and decimal part separately as integers (e.g use fmod from cmath to get the decimal part, multiply it by 10000000 and round to integer).
As a general case, floating point representation has no notion of "digits". It is just a binary approximation of the value.
Is there any formatting flag that makes it possible to print decimal values with required precision?
Frankly, I would just go with:Quote:
Originally Posted by forumuser
which is what I told you in post #4.Code:std::cout.precision(8);
sorry but why u dont use printf("%f",float); to express your float?
1. It is not allowed.Quote:
Originally Posted by punkywow
2. It will not help anyway (but then the question is flawed to begin with).
This is probably going to come as a total shock, and you might even be tempted to not believe it at first, but the variable "i" does not contain the value 9.8754321 in that piece of code. A float is an approximation which only holds about 6 significant figures. You can try and assign it a number with as many digits to the right of the decimal point as you like but the actual number it holds will only contain about 6 significant figures. In the above case "i" is 9.8754320 on a typical PC, and that's actually quite lucky, as often the number will be even less accurate than that.
What Every Computer Scientist Should Know About Floating-Point Arithmetic