Please note that this is a learning note.
This time, we will calculate the sum of integers of 5 or more.
Input example 1
1
3
Output example 1
0
Input example 2
9
2
-3
-3
4
-1
6
4
5
8
Output example 2
19
loop = gets.chomp.to_i
ans = 0 //Set initial value
(1..loop).each do |i|
num = gets.chomp.to_i
if num >= 5
ans = ans + num
end
end
puts ans
loop = gets.chomp.to_i
gets.chomp.to_i
gets the first line (9 in Example 2)
-Get the input value with the gets method
-Chop method: Removes line breaks in character strings.
-To_i method: Converts a character string to an integer
(1..loop).each do |i|
The value after 1 of the value assigned to the loop with (1..loop)
is repeatedly extracted and the variable i
Substituted in (obtain the second and subsequent lines (2 -3 -3 4 -1 6 4 5 8 in Example 2))
num = gets.chomp.to_i
Convert the value assigned to the variable i to an integer again and assign it to num
if num >= 5
ans = ans + num
end
Add to ans only when num is 5 or more in the if statement
I didn't understand why I needed to convert it to an integer again in each statement.
Thank you for your professor!
Recommended Posts