Try the fastest way to create flashcards
Question

Trace the program carefully and show the output of the following code. Rational r1 = new Rational(1, 2); Rational r2 = new Rational(1, -2); System.out.println(r1.add(r2));

Solution

Verified
Answered 2 years ago
Answered 2 years ago
Step 1
1 of 2

The result should be 0, so numerator is correct. Denominator is 4 because of second line in add function:

long d = denominator * secondRational.getDenominator();\texttt {long d = denominator * secondRational.getDenominator();},

that is d = 2*2 = 4.

secondRational.denominator is 2, and not -2 because minus is moved to numerator in constructor. So secondRational.numerator is -1.

Create a free account to view solutions

Create a free account to view solutions

Recommended textbook solutions

Computer Organization and Design MIPS Edition: The Hardware/Software Interface 5th Edition by David A. Patterson, John L. Hennessy

Computer Organization and Design MIPS Edition: The Hardware/Software Interface

5th EditionISBN: 9780124077263David A. Patterson, John L. Hennessy
226 solutions
Intro to Java Programming, Comprehensive Version 10th Edition by Y. Daniel Liang

Intro to Java Programming, Comprehensive Version

10th EditionISBN: 9780133761313Y. Daniel Liang
1,628 solutions
Fundamentals of Database Systems 7th Edition by Ramez Elmasri, Shamkant B. Navathe

Fundamentals of Database Systems

7th EditionISBN: 9780133970777Ramez Elmasri, Shamkant B. Navathe
948 solutions
Introduction to Algorithms 3rd Edition by Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen

Introduction to Algorithms

3rd EditionISBN: 9780262033848Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen
872 solutions

More related questions

1/4

1/7