日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

ruby 将字符转数字计算_Ruby程序计算一个数字中的位数

發(fā)布時間:2025/3/11 编程问答 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ruby 将字符转数字计算_Ruby程序计算一个数字中的位数 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

ruby 將字符轉(zhuǎn)數(shù)字計算

計算位數(shù) (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沒有為您提供任何預(yù)定義的直接方法,通過該方法可以找到數(shù)字中的數(shù)字位數(shù) 。 盡管可以通過將數(shù)字轉(zhuǎn)換為字符串然后對它應(yīng)用.length方法來實現(xiàn)一種方法。 在這種情況下,表達式將看起來像“ number.to_s.length”,但這需要將數(shù)字轉(zhuǎn)換為字符串。 如果您不想應(yīng)用此類方法,則可以使用下面給出的代碼。

Methods used:

使用的方法:

  • puts: This method is a predefined method which is used to print a string on the console.

    puts :此方法是預(yù)定義的方法,用于在控制臺上打印字符串。

  • 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 :此變量存儲用戶提供的數(shù)字。

  • 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 :這是一個計數(shù)器變量。 它存儲num中可用的位數(shù)。

Ruby代碼來計算數(shù)字中的位數(shù) (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 digits

Code 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 ,它作為一個計數(shù)器并在計數(shù)位數(shù)。 計數(shù)由0初始化,并在使用while循環(huán)提及的條件成立時遞增。 每次迭代后,該數(shù)字將除以10。 代碼并不復(fù)雜,很容易理解。

翻譯自: https://www.includehelp.com/ruby/count-the-number-of-digits-in-a-number.aspx

ruby 將字符轉(zhuǎn)數(shù)字計算

總結(jié)

以上是生活随笔為你收集整理的ruby 将字符转数字计算_Ruby程序计算一个数字中的位数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。