ruby打印
打印乘法表 (Printing multiplication table)
This requires a very simple logic where we only have to multiply the number with digits from 1 to 10. This can be implemented by putting the multiplication statement inside a loop. We have mentioned two ways: one is by using while loop and the second one is by making use of for loop. When you are using while loop, first you will have to initialize i with 1 and increment it by 1 inside the loop. for loop, the method is simpler as it only requires the specification of for keyword along with the range on which the loop is going to work.
这需要非常简单的逻辑,其中我们只需要将数字与1到10的数字相乘即可。这可以通过将乘法语句放入循环中来实现。 我们提到了两种方法:一种是使用while循环,第二种是使用for循环 。 使用while循环时,首先必须在循环内将i初始化为1并将其递增1。 for循环 ,该方法更简单,因为它只需要指定for关键字以及循环将要作用的范围。
Methods used:
使用的方法:
puts: This is a predefined method which is used to put the string on the console.
puts :这是一种预定义的方法,用于将字符串放置在控制台上。
gets: This is also a predefined method in Ruby library which is used to take input from the user through the console in the form of string.
gets :这也是Ruby库中的预定义方法,用于通过控制台以字符串形式从用户获取输入。
*: This is an arithmetic operator commonly known as multiplication operator which takes two arguments and process them by giving out their product as a result.
* :这是一种算术运算符,通常称为乘法运算符,它接受两个参数,并通过将其结果作为乘积进行处理。
Variables used:
使用的变量:
num: This variable is used to store the integer provided by the user.
num :此变量用于存储用户提供的整数。
mult: This is storing the result for i*num.
mult :这将存储i * num的结果。
i: This is a loop variable which is initialized by 1.
i :这是一个由1初始化的循环变量。
Ruby代码打印数字的乘法表 (Ruby code to print multiplication table of a number)
=begin
Ruby program to print multiplication table of
a number(by using for loop)
=end
puts "Enter the number:"
num=gets.chomp.to_i
for i in 1..10
mult=num*i
puts "#{num} * #{i} = #{mult}"
end
Output
输出量
Enter the number:
13
13 * 1 = 13
13 * 2 = 26
13 * 3 = 39
13 * 4 = 52
13 * 5 = 65
13 * 6 = 78
13 * 7 = 91
13 * 8 = 104
13 * 9 = 117
13 * 10 = 130
Method 2:
方法2:
=begin
Ruby program to print multiplication table of a
number(by using while loop)
=end
puts "Enter the number:"
num=gets.chomp.to_i
i=1
while (i<=10)
mult=num*i
puts "#{num} * #{i} = #{mult}"
i+=1
end
Output
输出量
Enter the number:
16
16 * 1 = 16
16 * 2 = 32
16 * 3 = 48
16 * 4 = 64
16 * 5 = 80
16 * 6 = 96
16 * 7 = 112
16 * 8 = 128
16 * 9 = 144
16 * 10 = 160
Code explanation:
代码说明:
The logic of code is pretty simple. In the first method, we are using while loop for the process and in the second one, we are using for loop. We have a variable mult in which we are multiplying the number with the i. The loop will terminate when i becomes equal to 10.
代码的逻辑非常简单。 在第一种方法中,我们使用while循环进行处理,在第二种方法中,我们使用for循环 。 我们有一个变量mult ,其中我们将数字乘以i 。 当我等于10时,循环将终止。
翻译自: https://www.includehelp.com/ruby/print-multiplication-table-of-a-number.aspx
ruby打印