ruby 将字符转数字计算_Ruby程序计算一个数字中的位数
ruby 將字符轉數字計算
計算位數 (Counting the number of digits)
Ruby does not provide you any predefined direct method through which you can find the number of digits in a number. Though one method can be implemented by converting the number into a string and then apply .length method to it. In that case, the expression will look like “number.to_s.length” but that requires conversion of number into a string. If you do not want to apply such type of method then you can go for the code given below.
Ruby沒有為您提供任何預定義的直接方法,通過該方法可以找到數字中的數字位數 。 盡管可以通過將數字轉換為字符串然后對它應用.length方法來實現一種方法。 在這種情況下,表達式將看起來像“ number.to_s.length”,但這需要將數字轉換為字符串。 如果您不想應用此類方法,則可以使用下面給出的代碼。
Methods used:
使用的方法:
puts: This method is a predefined method which is used to print a string on the console.
puts :此方法是預定義的方法,用于在控制臺上打印字符串。
gets: The gets method is used to get a string from the user through the console.
gets :gets方法用于通過控制臺從用戶獲取字符串。
Variables used:
使用的變量:
num: This variable is storing the number which is provided by the user.
num :此變量存儲用戶提供的數字。
temp: This is acting as the temporary variable which is storing the value available in num.
temp :這是一個臨時變量,用于存儲num中可用的值。
count: This is acting as a counter variable. It is storing the number of digits available in num.
count :這是一個計數器變量。 它存儲num中可用的位數。
Ruby代碼來計算數字中的位數 (Ruby code to count the number of digits in a number)
=begin Ruby program to count the number of digits =endputs "Enter the number:" num=gets.chomp.to_itemp=num count=0while (temp>0)count+=1temp=temp/10 endputs "#{num} has #{count} digits"Output
輸出量
RUN 1: Enter the number 89744 89744 has 5 digitsRUN 2: Enter the number 8171627331 8171627331 has 10 digitsCode explanation:
代碼說明:
You can observe in the above code that we have taken a variable count, which is behaving as a counter and counting the number of digits. The count is initialized by 0 and is incrementing when the condition mentioned with while loop is coming out to be true. The number is getting divided by 10 after every iteration. The code is not complex and is very easy to understand.
您可以在上面的代碼中觀察到我們采用了一個可變的count ,它作為一個計數器并在計數位數。 計數由0初始化,并在使用while循環提及的條件成立時遞增。 每次迭代后,該數字將除以10。 代碼并不復雜,很容易理解。
翻譯自: https://www.includehelp.com/ruby/count-the-number-of-digits-in-a-number.aspx
ruby 將字符轉數字計算
總結
以上是生活随笔為你收集整理的ruby 将字符转数字计算_Ruby程序计算一个数字中的位数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tohexstring方法_Java F
- 下一篇: ThreadLocal中的3个大坑,内存