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
=end

puts "Enter the number:"
num=gets.chomp.to_i

temp=num
count=0

while (temp>0)
	count+=1
	temp=temp/10
end

puts "#{num} has #{count} digits"

Output

输出量

RUN 1:
Enter the number
89744
89744 has 5 digits

RUN 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 ,它作为一个计数器并在计数位数。 计数由0初始化,并在使用while循环提及的条件成立时递增。 每次迭代后,该数字将除以10。 代码并不复杂,很容易理解。

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

ruby 将字符转数字计算

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值