C#中解析转换字符串后仍无法使用乘法运算符的问题
问题分析与解决
错误原因
你调用int.Parse()或Convert.ToInt32()时,只是执行了转换操作,但没有将转换后的整数结果赋值给新变量。原变量User_Length和User_Width始终是string类型,而C#不允许对字符串直接使用乘法运算符,因此触发Operator '*' cannot be applied to operands of type 'string' and 'string'错误。
修正后的代码
using System; public class Program { public static void Main() { Console.WriteLine("Hello, would you like me to calculate the area of your rectangle? input anything to continue."); Console.ReadLine(); Console.WriteLine("Please give me the Length of the rectangle:"); // 将输入转换为整数并保存到int类型变量 int length = int.Parse(Console.ReadLine()); Console.WriteLine("Please give me the Width of your rectangle"); int width = Convert.ToInt32(Console.ReadLine()); // 使用整数变量计算面积 Console.WriteLine("Here is the Area of your rectangle: " + (length * width)); } }
关键修改点
- 将用户输入的字符串直接转换为整数并赋值给
int类型变量(length和width),不再保留多余的字符串变量 - 计算面积时使用整数变量进行乘法运算,避免字符串类型的错误
额外建议:添加输入验证
如果用户输入非数字内容,int.Parse()会抛出异常,建议使用int.TryParse()做输入验证,提升程序稳定性:
using System; public class Program { public static void Main() { Console.WriteLine("Hello, would you like me to calculate the area of your rectangle? input anything to continue."); Console.ReadLine(); int length; while (true) { Console.WriteLine("Please give me the Length of the rectangle:"); if (int.TryParse(Console.ReadLine(), out length)) { break; } Console.WriteLine("Invalid input, please enter a number."); } int width; while (true) { Console.WriteLine("Please give me the Width of your rectangle"); if (int.TryParse(Console.ReadLine(), out width)) { break; } Console.WriteLine("Invalid input, please enter a number."); } Console.WriteLine("Here is the Area of your rectangle: " + (length * width)); } }
内容的提问来源于stack exchange,提问作者Dima
相关产品推荐
相关产品推荐

