Rust数学错误

huangapple go评论102阅读模式
英文:

Rust math error

问题

我在Rust中有以下代码:

fn main() {
    let mut sum = 0is;
    for i in (0is..100000000is) {
        sum = sum + i;
    }
    println!("{}", sum);
}

结果是4999999950000000。

但是,当我尝试使用Golang和Ruby检查这段代码时,我看到了另一个结果。

Golang版本:

package main

import "fmt"

func main() {
    var sum = 0
    for i := 1; i < 99999999; i++ {
        sum += i
    }

    fmt.Println(sum)
}

Ruby版本:

@sum = 0
(1...99999999).each do |i|
    @sum += i
end

puts @sum

Ruby和Golang的结果都是4999999850000001。

PS:是的,我知道100000000和99999999之间的差异是因为Rust中的0is..100000000is包含了右边界。

英文:

I have following code in Rust:

fn main() {

	let mut sum = 0is;
	for i in (0is..100000000is) {
		sum = sum + i;
	}
	println! (&quot;{}&quot;, sum);
}

as a result, I have 4999999950000000

But, when I try to check this code with Golang and Ruby - I see another result

golang version:

package main

import &quot;fmt&quot;

func main() {
  var sum = 0
  for i := 1; i &lt; 99999999; i++ {
      sum += i
  }

  fmt.Println(sum)
}

Ruby version:

@sum = 0
(1...99999999).each do |i|
  @sum += i
end

puts @sum

and the result for both Ruby and Golang is 4999999850000001

PS: yep, I know about difference between 100000000 and 99999999 - it's because of inclusion right part in Rust in 0is..100000000is

答案1

得分: 5

你在Go和Ruby中没有对最后一个元素(99999999)进行求和:

func main() {
    var sum = int64(0)
    for i := int64(1); i <= 99999999; i++ {
        sum += i
    }
    fmt.Println(sum)
}

4999999950000000
sum = 0
(1..99999999).each do |i|
    sum += i
end
puts sum

4999999950000000
英文:

You are not summing the last element (99999999) in Go and Ruby:

func main() {
	var sum = int64(0)
	for i := int64(1); i &lt;= 99999999; i++ {
		sum += i
	}
	fmt.Println(sum)
}

4999999950000000

huangapple
  • 本文由 发表于 2015年1月19日 18:01:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/28021991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定