ruby打印_Ruby程序打印一个数字的乘法表
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) =endputs "Enter the number:" num=gets.chomp.to_ifor i in 1..10mult=num*iputs "#{num} * #{i} = #{mult}" endOutput
輸出量
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 = 130Method 2:
方法2:
=begin Ruby program to print multiplication table of a number(by using while loop) =endputs "Enter the number:" num=gets.chomp.to_ii=1 while (i<=10)mult=num*iputs "#{num} * #{i} = #{mult}"i+=1 endOutput
輸出量
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 = 160Code 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打印
總結
以上是生活随笔為你收集整理的ruby打印_Ruby程序打印一个数字的乘法表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: scala 拆分字符串翻转_Scala程
- 下一篇: getminimum_Java Cale