Basically im trying to enter a value into the console, and output the decimal point as a whole number, and thats what needs to essentially occur.
I've developed a way to do this, using float, int and simple maths.
I'm still new to C++ but this error is not making sense.
If you enter 0.01, 0.02, 0.03, 0.04, 0.06 or 0.08 you get the wrong output.
I basically want to make it as simple as 0.06 * 100 = 6.
I'm pretty sure its a simple mistake, but why is this so, when clearly I'm entering a whole float number anyway.
#include <iostream>
using namespace std;
int main()
{
float input = 0;
while (input <= 0 || input > 999.99)
{
cout << "Please enter a number with decimal: ";
cin >> input;
}
int whole_num = input;
float to_decimal = input - whole_num;
int decimal = to_decimal * 100;
cout << decimal << endl;
return 0;
}
EDIT: I found the solution for my problem
There was a problem with the float accuracy. So far adding 0.5f to the int can fix the problem. I know it does it properly to input of 2 decimal places, not sure for other types.
Thanks to Frederik Slijkerman!
#include <iostream>
using namespace std;
int main ()
{
float asfloat = 0.03;
int asint = asfloat * 100;
int asint_fix = 0.5f + asfloat * 100;
cout << "0.03 * 100 = " << asint << endl;
cout << "0.03 * 100 (with the +0.5f fix) = " << asint_fix << endl;
return 0;
}
Returns:
0.03 * 100 = 2
0.03 * 100 (with the +0.5f fix) = 3
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…