### warning converting to int from double

Hi,

I am trying to write a Fraction class and getting the following warning when compiling my code :

Fraction.cpp: In constructor 'Fraction::Fraction(double)':
Fraction.cpp:8: warning :converting to 'int' from 'double'

My Fraction.cpp class looks like :

 ``1234567891011`` ``````#include "Fraction.h" Fraction::Fraction(int n, int d):num(n),den(d) { cout << This is double param constructor <

My Header Fraction.h is like :

 ``12345678910`` ``````class Fraction { int num; unsigned int den; public: Fraction(int = 1,int =1); Fraction(double); };``````

And the application main.cpp is as follows:

 ``12345678`` ``````int main() { Fraction f1(3,9); Fraction f2(8); return 0; }``````

Thanks.
Simons

Are you sure you want to have a Fraction constructor taking a double as argument?
The range of values that the type double can hold is greater than the range of values for the type int. So when a double value is converted to int you can get an incorrect result.
Thanks , it helped
Something like this (approximate conversion):

 ``123456789`` ``````#include // to a precision of three digits after the decimal Fraction::Fraction( double d ) : den(1000) // set denominator to 1000 { // set numerator to 1000 * d converted to an int num = std::round( dbl * den ) ; // C++11 num = int( dbl * den ) ; // C++98 }``````
Last edited on
 How can I get rid of the warning

It's easy enough to shut the warning up using a cast or a compiler directive. But that would just hide the problem.

What do you expect the double constructor to do?

`Fraction f2(0.25); // a fraction with num = 1, den = 4 ?? `

and

`Fraction f2(3.141592654); // ?? `

How do you real with the fact that not all floating point numbers are rational?

Andy

> What do you expect the double constructor to do?
> `Fraction f2(0.25); // a fraction with num = 1, den = 4 ?? `

Sets `num = 250` and `den = 1000` which is equivalent.

> the fact that not all floating point numbers are rational?

All floating point numbers (except infinity and NaN) are rational numbers.
(Adding a check for NaN or infinity would be a good idea.)
Well, that Fraction (double); in the header file is just a constructor for explicit conversion, double to fraction conversion.

How can I write the body of it in the implementation ?
Are you aware that floating point types like float and double are just approximations? Not all values can be stored exactly. One such value is 0.1.

 `` `` ``std::cout << std::setprecision(20) << 0.1 << std::endl; // prints 0.10000000000000000555 ``

If you do not round or handle it in a somehow special way and just treat 0.1 exactly the way it is you will not get the nice fraction 1/10 but something with much larger values.
Topic archived. No new replies allowed.