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 :
1 2 3 4 5 6 7 8 9 10 11
#include "Fraction.h"
Fraction::Fraction(int n, int d):num(n),den(d)
{
cout << This is double param constructor <<endl;
}
Fraction::Fraction(double d):num(d),den(0)
{
cout <<This is single param constructor <<endl;
}
My Header Fraction.h is like :
1 2 3 4 5 6 7 8 9 10
class Fraction
{
int num;
unsignedint den;
public:
Fraction(int = 1,int =1);
Fraction(double);
};
And the application main.cpp is as follows:
1 2 3 4 5 6 7 8
int main()
{
Fraction f1(3,9);
Fraction f2(8);
return 0;
}
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.
#include <cmath>
// 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
}
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.