0
Didn't know cpp misses that thing
https://code.sololearn.com/cRX5LzoGVV02/?ref=app It should output: 2.99999
6 Réponses
+ 3
Add #include <iomanip> but remove #include <cmath>, it wasn't necessary for multiplication.
(Edited)
std::cout << std::setprecision(10) << c;
+ 3
Not "fix", but show you more precision...
std::cout.precision(10);
std::cout << ...
2.999997203
I'd use that carefully if you're answering a question elsewhere. All I'm doing is arbitrarily showing more digits, when the task might be to deal with rounding (this is not a solution in that case, because reducing the precision will round back up to 3)
(This answer may facilitate that solution though)
+ 2
Ipang - I didn't mean to disrupt your answer; I actually didn't see it before posting. That said, I was just testing, hung + lost the editor so...from memory:
Why they're different...
(I thought) rounding behavior and (I think) what default and fixed modes consider to be significant digits.
Yes, default precision is 6.
The class method cout.precision and stream modifier setprecision() appear to be interchangeable.
I tried two rounding modes (set by fesetround() : "to nearest" or "round downward"), but both produced the table below.
Fixed output is closer than non-fixed but still not quite as requested:
precision normal fixed
5 3 3.00000
6 3 2.999997
7 2.999997 2.9999972
This also rounds:
printf("%.5f", c);
What works:
Multiply c by 100000, std::trunc (from cmath), then divide again by 100000.
+ 2
Kirk Schafer Thanks again for explaining, I didn't know I/O manipulator affects rounding operations, learned a new thing from this.
+ 1
Kirk Schafer Thanks for correction, I revise my post, can you explain why the output with std::fixed yields nearly the same result, except for the number of decimal points?
Quoted from cplusplus:
"When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field(precision) and with no exponent part."
It did say as many digits in decimal part, and default precision was 6 digits (cmiiw)
0
Do you know how to fix this?