【问题标题】:Building a ruby factorial calculator构建一个红宝石阶乘计算器
【发布时间】:2015-02-16 04:33:58
【问题描述】:

我正在用 ruby​​ 编写一个阶乘程序,我正在尝试将其编写如下:

  1. 要求用户输入一个值以对其执行阶乘
  2. 接受输入的值
  3. 对其执行阶乘 4. 使用“puts”返回阶乘值

我的目标是让它发挥作用,然后通过构建它来扩展它以包含其他统计功能。

到目前为止,这是我拥有的代码:

puts "Welcome to the Calculator for Ruby"
puts "Please enter your value to value"

#N factorial value
def n
n = gets.chomp
end
def fact   
    n * fact(n-1)  

end  
puts fact(n) 

仅供参考,我可能会补充说,我已经看到了网络上可用的通用阶乘代码,但我想做的是设置它以便用户定义 n 而不是静态设置 n 但是当我尝试这样做时,我上面的代码出错并显示以下错误消息: “事实”:参数数量错误(1 代表 0)(ArgumentError)

对于其中的一些措辞,但不包括具体问题,我深表歉意。我的问题是 3 个部分:

  1. 如何正确编写阶乘计算以对用户提供的值进行操作? (我看到有人回答了)。

  2. 计算完成后,我如何存储该值,以便在用户想调用它进行其他计算时保留它。

  3. 最后,在用 ruby​​ 编写统计函数时,是否有任何好的指导资源?

感谢大家的帮助

【问题讨论】:

  • Ruby factorial function 的可能重复项
  • 你有什么问题?
  • 提示:错误信息准确地告诉你你需要知道什么。

标签: ruby statistics factorial


【解决方案1】:
  1. 无需使用def 声明n,只需分配它(例如n = gets.chomp)。

  2. 您必须在fact 函数中包含一个命名参数,例如def fact(x)

  3. fact(x) 函数需要一个基本情况,因为您使用的是递归。

  4. 您必须将用户输入字符串n 转换为数字,例如n.to_i

puts "Welcome to the Calculator for Ruby"
puts "Please enter your value to value"
def fact(x)
  (x <= 1) ? 1 : x * fact(x-1)
end  
n = gets.chomp.to_i
puts "#{n}! => #{fact(n)}"

【讨论】:

    【解决方案2】:

    更简单的方法。只需注入从 1 到 n 的数字。

    puts 'Welcome to the Calculator for Ruby'
    puts 'Please enter your value to value'
    n = gets.chomp.to_i
    puts (1..n).inject(:*)
    

    【讨论】:

    • 你甚至可以省略种子值 (1) 而只是 inject(:*)
    【解决方案3】:

    可能不是最好的解决方案,但你可以这样做

    puts "Welcome to the Factorial Calculator for Ruby"
    puts "Please enter your value to exaluate"
    
    n = gets.chomp.to_i
    
    def fact(num)
        return num <= 1 ? 1 : num * fact(num - 1)
    end
    
    puts "The factorial of #{n} is #{fact(n)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多