Reputation: 420
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.
Upvotes: 3
Views: 197
Reputation: 1184
Instead of reading it as a double, read it as a string and parse it. You won't run into floating precision problem that way.
Upvotes: 1
Reputation: 63250
Your problem is that you never initialize b
and therefore have undefined behaviour.
You should do this:
long b = 0;
Now you can go compare b with something else and get good behaviour.
Also comparing a float
with an integral
type should be done like comparing to an appropriate epsilon value:
while(fabs(an_int - a_float) < eps)
Upvotes: 2
Reputation: 29976
long b;
Here you define b
. From this point, the variable contains garbage value. The value can be absolutely random, basically it's just what happened to be in the memory when it was allocated. After that you are using this variable in a condition:
while(b!=a)
This will lead to undefined behaviour, which basically means that anything can happen, including an opportunity that the app will seem to be working (if you are lucky), based on the garbage value that is in b
.
To avoid this, you will need to initialize the b
with some value, for example, long b = 0
.
Upvotes: 0
Reputation: 76438
The problem is that most decimal values cannot be represented exactly as floating-point values. So having a decimal value that only has a couple of digits doesn't guarantee that multiplying by ten enough times will produce a floating-point value with no fractional part. To see this, display the value of a
each time through the loop. There's lots of noise down in the low bits.
Upvotes: 2
Reputation: 92331
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.
Upvotes: 4