0

这是从http://www.zenspider.com/ZSS/Products/RubyInline/Readme.html复制的,rubyinline 的“家”,添加/修改如评论中所示

require 'rubygems' #added this, doesn't run otherwise
require 'inline'
class MyTest

  def factorial(n)
    f = 1
    n.downto(2) { |x| f *= x }
    f
  end

  inline do |builder|
    builder.c "
    long factorial_c(int max) {
      int i=max, result=1;
      while (i >= 2) { result *= i--; }
      return result;
    }"
  end
end

#t = MyTest.new()  # removed this
#factorial_5 = t.factorial(5) # removed this

asdf = MyTest.new # added this
puts "ruby native factorial: " + asdf.factorial(16).to_s # added this
puts "inline factorial: " + asdf.factorial_c(16).to_s # added this

当我运行它时,我得到

ruby testfact.rb

红宝石原生阶乘:20922789888000

内联阶乘:2004189184

红宝石版本是正确的;我不知道内联版本是什么(不正确除外)。

我正在运行 ruby​​ 1.8.7 (2008-08-11 patchlevel 72) [i486-linux];我这样安装了 ruby​​inline: sudo gem install RubyInline

我尝试在 C 代码中将“int”更改为“long”,但没有产生差异。(我不是 C 程序员,如果这还不明显的话。)

最后,我注意到如果我以 12 或更少作为参数运行它们,它们都会产生相同的答案。13岁及以上的事情变得很奇怪。

TIA

4

2 回答 2

1

你的 C 整数绝对是 32 位。

2 的 32 次方是 4294967296。

20922789888000 mod 4294967296 是 2004189184。

于 2009-09-03T02:49:00.570 回答
0

在 C 版本中,您拥有的是长 32 位还是 64 位?在 C 中,long 并不总是比 int 大。

于 2009-09-03T02:37:58.060 回答