这是从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];我这样安装了 rubyinline: sudo gem install RubyInline
我尝试在 C 代码中将“int”更改为“long”,但没有产生差异。(我不是 C 程序员,如果这还不明显的话。)
最后,我注意到如果我以 12 或更少作为参数运行它们,它们都会产生相同的答案。13岁及以上的事情变得很奇怪。
TIA