You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust函数未返回预期结果:sum(1,1)得0而非2,求原因及修复方法

问题原因与修复方案

问题原因

在sum函数内部,你通过let beams: u32 = 0;和let columns: u32 = 0;重新声明了与参数同名的变量,这会覆盖原本传入的函数参数值。不管调用时传入什么数值,函数实际计算的都是0 + 0,所以返回结果固定为0。

修复方法

删除函数内部重新声明变量的两行代码,直接使用传入的参数进行加法运算即可。

修复后的完整代码:

// Calculate the weight of a building

fn main() {
    let weight = sum(1, 1); //calling sum(1,1) and trying to bind its result to a variable
    println!("The result is {}.", weight); //printing "weight"
}

//function to perform "beams + columns" and use it in main()
fn sum(beams: u32, columns: u32) -> u32 {
    beams + columns //Trying to return the result
}

内容的提问来源于stack exchange,提问作者Remi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:05:23