We will get the tens and ones digits from a two-digit integer and write until the calculation result is output.
--Practice --Problem --Answer (commentary) --Another solution (digits method) --Another solution (divmod method)
--Summary
--References
Write a program that adds ** addition and multiplication results ** of ** 10's and 1's ** numbers from a two-digit integer and outputs it.
answer
def addition(a, b)
a + b
end
#Multiplication of tens and ones
def multiplication(a, b)
a * b
end
def check_num(num)
tens_place = (num / 10) % 10 #The remainder is calculated after dividing the tens digit by 10 to make it one digit.
ones_place = num % 10 #The remainder when divided by 10 is the 1st place
addition_result = addition(tens_place, ones_place) #Add with the addition method
multiplication_result = multiplication(tens_place, ones_place) #Multiply with multiplication method
p "The sum of the result of addition and the result of multiplication is#{ addition_result + multiplication_result }is."
end
#Enter in the terminal
p 'Please enter a two digit integer'
num = gets.to_i
#Method call
check_num(num)
The rewritten part is where ** 10's place and 1's place are calculated **. The reason for specifying 2 in the argument of digits.take is that we are getting two values, the ones digit and the tens digit. Note that when you get it with digits.take, you get it in order from 1's place.
digits
def addition(a, b)
a + b
end
def multiplication(a, b)
a * b
end
def check_num(num)
ones_place, tens_place = num.digits.take(2) #Get 1st and 10th place
addition_result = addition(tens_place, ones_place)
multiplication_result = multiplication(tens_place, ones_place)
p "The sum of the result of addition and the result of multiplication is#{ addition_result + multiplication_result }is."
end
p 'Please enter a two digit integer'
num = gets.to_i
check_num(num)
The rewritten part is where ** 10's place and 1's place are calculated **. By specifying a numerical value in the argument of divmod ( 10 in this case), you can get the quotient and remainder when divided.
divmod
def addition(a, b)
a + b
end
def multiplication(a, b)
a * b
end
def check_num(num)
tens_place, ones_place = num.divmod(10) #Get 1st and 10th place
addition_result = addition(tens_place, ones_place)
multiplication_result = multiplication(tens_place, ones_place)
p "The sum of the result of addition and the result of multiplication is#{ addition_result + multiplication_result }is."
end
p 'Please enter a two digit integer'
num = gets.to_i
check_num(num)
――The tens place is the remainder of dividing a two-digit integer by 10 and then dividing by 10. ――The ones digit is the remainder of dividing a two-digit integer by 10. --By using the digits method, you can get the numbers in order from the 1st place.
-Ruby 2.7.0 Reference Manual (digits) -Ruby 2.7.0 Reference Manual (divmod) -Get tens and ones digits from two digits -Find the quotient and remainder of division at once
Recommended Posts