为何我的C#程序输出年龄为181而非预期的19?
字符串拼接优先级导致整数加法异常问题
问题描述
需要编写程序实现:让用户输入姓名和当前年龄,输出个性化问候并告知其下一次生日的年龄。例如输入“Kelly”和“43”,应输出Hello Kelly, on your next birthday you will be 44.。
但当前代码运行异常:输入年龄18时,输出内容为Hello earl, on your next birthday you will be 181,而非预期的Hello earl, on your next birthday you will be 19。
用户提供的代码如下:
string name, input; int age; Console.WriteLine("What is your name?"); name= Console.ReadLine(); Console.WriteLine("What is your age?"); input = Console.ReadLine(); age = Convert.ToInt32(input); Console.WriteLine("Hello " + name + ", on your next birthday you will be " + age + 1); Console.ReadLine();
问题原因
这是C#中+运算符的优先级和类型转换规则导致的:
- 当
+运算符混合字符串和整数操作数时,会优先将整数转换为字符串,执行字符串拼接操作,而非整数加法。 - 原代码中
"Hello " + name + ", on your next birthday you will be " + age + 1的执行顺序是:- 先拼接前面的字符串和
age,得到"Hello earl, on your next birthday you will be 18" - 再将这个结果和整数
1拼接,最终得到"Hello earl, on your next birthday you will be 181"
- 先拼接前面的字符串和
解决方案
有两种常见的修复方式:
方式1:用括号强制优先执行整数加法
把age + 1用括号包裹,让加法运算先于字符串拼接执行:
string name, input; int age; Console.WriteLine("What is your name?"); name= Console.ReadLine(); Console.WriteLine("What is your age?"); input = Console.ReadLine(); age = Convert.ToInt32(input); // 给age + 1添加括号,确保先计算加法 Console.WriteLine("Hello " + name + ", on your next birthday you will be " + (age + 1)); Console.ReadLine();
方式2:使用字符串插值(推荐)
C#的字符串插值语法($"")更直观,能避免这类优先级问题,代码可读性更高:
string name, input; int age; Console.WriteLine("What is your name?"); name= Console.ReadLine(); Console.WriteLine("What is your age?"); input = Console.ReadLine(); age = Convert.ToInt32(input); // 使用字符串插值直接嵌入表达式 Console.WriteLine($"Hello {name}, on your next birthday you will be {age + 1}."); Console.ReadLine();
内容的提问来源于stack exchange,提问作者Cutty
相关产品推荐
相关产品推荐

