我试图在Project Euler中为问题6编写一个rubysh解决方案,因为我有用其他语言编写C的倾向但是,此代码:

sqrsum, sumsqr = 0, 0
(1..100).each { |x| sqrsum, sumsqr += x, x**2 }
p (sumsqr - (sqrsum ** 2))

引发这些错误:
/Users/Andy/Documents/Programming/Ruby/ProjectEuler/P6.rb:2: syntax error, unexpected tOP_ASGN, expecting '='
(1..100).each { |x| sqrsum, sumsqr += x, x**2 }
                                     ^
/Users/Andy/Documents/Programming/Ruby/ProjectEuler/P6.rb:2: syntax error, unexpected tPOW, expecting '='
(1..100).each { |x| sqrsum, sumsqr += x, x**2 }
                                            ^

我在这里做错什么了我只能在那个句法结构中赋值吗?

最佳答案

您正在尝试进行多个赋值,但您没有使用赋值运算符=
比较sqrsum, sumsqr = 0, 0sqrsum, sumsqr += x, x**2
可能你想写sqrsum, sumsqr = sqrsum+x, sumsqr+x**2

07-24 09:54