I am a programming newbie. I needed a simple function to convert any number with decimal point X.YZ into XYZ. I did it by multiplying it by 10 enough times and using double to int conversion.
int main()
{
std::cout << "Number: " << std::endl;
double a;
// the uninitialized b was pointed out, its not the issue
long b = 0;
std::cin >> a;
while(b!=a)
{
a*=10;
b=a;
}
std::cout << a << std::endl;
return 0;
}
This works like 90 percent of the time. For some numbers like 132.54, the program runs infinitely long. It processes 132.547(which should use more memory then 132.54) the way it should.
So my question is : Why is it not working 100 percent for the numbers in the memory range of long int? Why 132.54 and similar numbers?
I am using Codeblocks and GNU GCC compiler.
Many decimal floating point numbers cannot be exactly represented in binary. You only get a close approximation.
If 132.54 is represented as 132.539999999999999, you will never get a match.
Print the values in the loop, and you will see what happens.