i am writing a function to convert fractions to intgers for example:
.636 -> 636 or .45 -> 45

int ret_int(double input)
{
	while(true)
	{
                // this line is for debugging only
	cout  << input << "  "  << floor(input) << endl;

	if(input == floor(input)) return input;
	input = input * 10;
	}
}

for some inputs it is working fine for example:

But for some inputs :


which i cant understand the floor and the input are the same so why the function does not return

some inputs also do this:


floor(23450) = 23499

weird?
if anybody has another approach (another method) to do the job i would be thankful

Attachments 1.jpg 20.4 KB 3.jpg 25.45 KB

I had very similar output in one of my project, it seems I declared a double somewhere, but didn't instantiate it...

double somedouble;

I don't know if this is applicable to you, but now that I've instantiated it, it seems to be better...

double somedouble = 0.0;

Remember: 2.0+2.0!=4.0. I think this is just roundoff error, .245*1000 can be smaller then 245.
edit: Solution: define new class for double and make new operator== which will do something like that:

if(a<b*(1+epsilon) && a>b*(1-epsilon)) return true;
return fals;

where epsilon is desired precision (10**-10 would be good).

Edited 7 Years Ago by Zjarek: n/a

constructing a whole class to solve such a problem!
is nt there any simpler solutions

ok i did what the website told me to do , writing a function to check if two double numbers are equal or not , this solved the first problem when the input is .23 for eample (see the second picture in my first post)

but it did not solve the second problem (see the third picture in my first post) : floor(2345) = 2344

this is a problem with the floor function .

any suggestions !

This article has been dead for over six months. Start a new discussion instead.