英文:
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! ("{}", 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 "fmt"
func main() {
var sum = 0
for i := 1; i < 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 <= 99999999; i++ {
sum += i
}
fmt.Println(sum)
}
4999999950000000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论