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

C#中计算两数和未加括号输出510的原因是什么?

为什么C#中未加括号时输出510而非15?

先看你的示例代码:

Console.WriteLine("Enter the numbers you want to sum in order:");
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("the sum of the numbers you entered : " + num1 + num2);
Console.Read();

当输入5和10时,这段代码会输出the sum of the numbers you entered : 510而非预期的15,核心原因是运算符的执行顺序:

  • C#中,字符串拼接的+和算术加法的+优先级相同,执行顺序为从左到右。
  • 代码里的表达式"the sum of the numbers you entered : " + num1 + num2会先执行左侧的字符串拼接:把固定字符串和num1(值为5)拼接成新字符串"the sum of the numbers you entered : 5"。
  • 接着用这个新字符串和num2(值为10)做第二次字符串拼接,最终得到拼接后的结果510。

如果给num1 + num2加上括号,就会强制先执行算术加法运算:(num1 + num2)先算出15,再和前面的字符串拼接,就能得到预期的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:45:37