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
相关产品推荐
相关产品推荐

