打印

[一般问题] 菜鸟的问题:求和

菜鸟的问题:求和

菜鸟的问题:请问给出一个n(interger),如何求从1到N的和?

TOP

用循环语句求。

Thank you very much, I am waiting online

TOP

已经解决!如下

question:

Problem 2 Make a program that accepts a number as input, and outputs the sum of a series
of numbers (1,2,3,4,5....) up to the input number.

Key:
print "Sum number:"
n = gets.to_i

s=0
for i in 1..n
  s=s+i
end 
  
 puts s


Thank you for your concern!
本帖最近评分记录
  • drive2me R币 +5 鼓励自问自答。 2008-8-19 23:55

TOP

也可以这样做,写一个方法来实现,如下所示

def totalSum(n)
 sum = 0
 n.downto(1) {|i| sum += i }
 return sum
end

puts totalSum(10), ""
puts totalSum(100), ""
本帖最近评分记录
  • drive2me R币 +5 谢谢解答。 2008-8-19 23:55

TOP

(1+n)*n/2
本帖最近评分记录
  • drive2me R币 +5 谢谢解答。 2008-8-19 23:55

TOP

引申一下 參考樓上的

利用等差數列的求和公式
def intSum(intS,intE)
 return (intS+intE)*(intE-intS+1)/2
end
p intSum(1,100)  # 5050
這個效率比循環快很多 樓主可以試下
本帖最近评分记录
  • drive2me R币 +5 谢谢! 2008-8-21 23:21
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
 建議是發展的基石,批評是前進的動力。大家來P吧,莫客氣 
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※

TOP

他的需求是1..N的和,所以也没什么必要-1+1了……

TOP

$s=0
1.upto(n){|i| $s+=i}
puts $s

TOP

2008-12-02 10:38 Crawled by CCBot/1.0 (+http://www.commoncrawl.org/bot.html) @38.103.63.61