long to double trouble (Rhyme scheme not intended)

Printable View

• 08-18-2009, 07:03 PM
sdeverteuil
long to double trouble (Rhyme scheme not intended)
Hello. As of lately I have been messing around with the Fraction class in type.lib, trying to get myself acquainted with it. Anyhow, for practice, I've been writing a simple program that computes 4 fractions in the equation

A=(x + y)/(z +t) where x, y, z, and t are the 4 fractions.

The constructor takes long values of course. However, I intend for my program to print the preceding equation as an improper fraction, a proper fraction, and then an approximate real value using double precision. Here is an outline of my program.
Code:

```          //Print instructions.           output.println("Enter each fraction, enter its            numerator/denominator,");           output.println("pressing enter after each.");                           //Prompt and input.           output.println("Enter x.");           long a = input.nextLong();           long b = input.nextLong();           output.println("Enter y.");           long c = input.nextLong();           long d = input.nextLong();           output.println("Enter z.");           long e = input.nextLong();           long f = input.nextLong();           output.println("Enter t.");           long g = input.nextLong();           long h = input.nextLong();                           //Assign and compute.           Fraction x = new Fraction(a, b);           x.add(new Fraction(c, d));           Fraction z = new Fraction(e, f);           z.add(new Fraction(g, h));           x.divide(z);           x.isQuoted = false;                     double numerator = ((a / b) + (c / d));           double denominator = ((e / f) + (g / h));           double answer = (numerator / denominator);                     //output           output.print("A = ");           output.print(x.toString());           output.print(" = ");           output.print(x.toProperString());           output.print(" = ");           output.println(answer);```
When printing out the approximate real value, the output sometimes comes out as NaN which I assume stands for not a number. This is because the two fractions that I used for the overall denominator of the equation get automatically rounded down to zero I expect.

Does anyone have any suggestions? :)
• 08-18-2009, 09:50 PM
Fubarable
You're running into "int" or here long division problems. Please understand that an int/int will return an int not a double, and likewise a long/long will return a long. The compiler will throw out anything past the decimal point rounding the answer down if positive and up if negative. You will want to cast one of the numbers as double first before dividing. e.g.,:

Code:

`double numerator = (((double)a / b) + ((double)c / d));`
• 08-18-2009, 11:02 PM
sdeverteuil
Thank you very much! That fixed the problem. I'll remember that.

~cheers