0

Didn't know cpp misses that thing

https://code.sololearn.com/cRX5LzoGVV02/?ref=app It should output: 2.99999

19th Sep 2018, 3:23 PM
Oleg Storm
Oleg Storm - avatar
6 Réponses
+ 3
Add #include <iomanip> but remove #include <cmath>, it wasn't necessary for multiplication. (Edited) std::cout << std::setprecision(10) << c;
19th Sep 2018, 3:46 PM
Ipang
+ 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)
19th Sep 2018, 3:48 PM
Kirk Schafer
Kirk Schafer - avatar
+ 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.
20th Sep 2018, 6:49 AM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Kirk Schafer Thanks again for explaining, I didn't know I/O manipulator affects rounding operations, learned a new thing from this.
20th Sep 2018, 7:03 AM
Ipang
+ 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)
19th Sep 2018, 4:02 PM
Ipang
0
Do you know how to fix this?
19th Sep 2018, 3:23 PM
Oleg Storm
Oleg Storm - avatar