+ 2
What happened? Why 7.8999 7.99999 8.09999?
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
+ 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
+ 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
+ 1
thanks everyone.
almost understand.
English isn't my best.
0
Seems to be a bug in the compiler?! I even tried printf to get better results: https://code.sololearn.com/cfH4jzR2TtwP/#c
0
@jay this does fix the output issue but why doen't it add two numbers correctly?