+ 2

What happened? Why 7.8999 7.99999 8.09999?

https://code.sololearn.com/c1M0l88iXwdL/?ref=app

21st Mar 2018, 2:11 PM
igor
igor - avatar
6 Answers
+ 11
try: #include <iostream> #include <ios> using namespace std; int main() { float num = 1; cout.precision(2); while (num < 9) { cout << "Number: " << num << endl; num = num + .1; } return 0; } https://code.sololearn.com/cCiVS7gbvy0L/?ref=app Explanation: https://docs.microsoft.com/en-au/cpp/build/reference/why-floating-point-numbers-may-lose-precision
21st Mar 2018, 2:35 PM
jay
jay - avatar
+ 9
See link to Microsoft document (just edited) Floating-point decimal values generally do not have an exact binary representation. This is a side effect of how the CPU represents floating point data. For this reason, you may experience some loss of precision, and some floating-point operations may produce unexpected results
21st Mar 2018, 2:48 PM
jay
jay - avatar
+ 9
This reference page may also help. http://www.cplusplus.com/reference/ios/ios_base/precision/ and here is an alternate source for an explanation of the error you encountered https://wiki.sei.cmu.edu/confluence/plugins/servlet/mobile?contentId=87152394#content/view/87152394
21st Mar 2018, 3:03 PM
jay
jay - avatar
+ 1
thanks everyone. almost understand. English isn't my best.
21st Mar 2018, 2:54 PM
igor
igor - avatar
0
Seems to be a bug in the compiler?! I even tried printf to get better results: https://code.sololearn.com/cfH4jzR2TtwP/#c
21st Mar 2018, 2:31 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
0
@jay this does fix the output issue but why doen't it add two numbers correctly?
21st Mar 2018, 2:47 PM
Aaron Eberhardt
Aaron Eberhardt - avatar