Question: home / study / engineering / computer science / computer science questions and answers / ruby programming write a program using the given fraction class
home / study / engineering / computer science / computer science questions and answers / ruby programming write a program using the given fraction class that asks the user to enter ...
Question: Ruby Programming Write a program using the given fraction class that asks the user to enter a num...
Ruby Programming
Write a program using the given fraction class that asks the user to enter a number and calculates the harmonic sum up to that number. hn = 1/1 + 1/2 + 1/3 + + 1/(n 1 )+ 1/n (i.e. h5 = 137/60)
If the user enters 5, the program should calculate and display h1,h2,h3,h4, and h5 like
$What harmonic sums do you wish to calculate? 5 h1: 1/1 h2: 3/2 h3: 11/6 h4: 25/12 h5: 137/60
Given Fraction Class:
class Fraction attr_accessor :numerator, :denominator
# constructor: initialize with a numerator and denominator # parameters: a numerator and denominator # return value: n/a def initialize(n, d) @numerator = n @denominator = d end
# +: syntactic sugar to sum a fraction and another value # parameters: a fraction object as the rightmost operand # return value: a new fraction object containing the sum def +(rhs) # calculate the values of the numerator and denominator n = @numerator*rhs.denominator + @denominator*rhs.numerator d = @denominator*rhs.denominator
# reduce the fraction to the lowest common term n, d = reduce(n, d)
return Fraction.new(n, d) end
# print: displays the fraction in the normal way # parameters: none # return value: none def print puts "#{@numerator} / #{@denominator}" end
# reduce: reduces a fraction to the lowest common denominator # parameters: a numerator and denominator # return value: the reduced numerator and denominator def reduce(n, d) r = gcd(n, d) return n / r, d / r end
# gcd: find the greatest common divisor using Euclid's algorithm # parameters: two integers # return value: the greatest common divisor def gcd(a, b) if a % b == 0 return b else return gcd(b, a % b) end end
private :reduce, :gcd end
# Write your code here.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
