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

使用Console.ReadLine()实现两数相加时遇“Invalid expression term 'int'”错误求助

问题解决:Invalid expression term 'int'

你的错误出在字符串转整数的语法上——C#不支持int(number1)这种写法,这是Python等其他语言的语法。在C#里,需要用专门的类型转换方法来实现字符串到整数的转换。

基础修复方案

使用int.Parse()方法来转换字符串,这是最直接的方式,修改后的代码如下:

using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Enter a number:");
      string number1 = Console.ReadLine();
      Console.WriteLine("Enter another number:");
      string number2 = Console.ReadLine();
      Console.WriteLine("The sum of those numbers is:");
      Console.WriteLine(int.Parse(number1) + int.Parse(number2));
    }
  }
}

更安全的进阶方案

如果用户输入的不是有效整数(比如字母、符号),int.Parse()会直接抛出异常导致程序崩溃。更稳妥的方式是使用int.TryParse(),它会返回一个布尔值告知转换是否成功,同时通过out参数输出转换后的整数:

using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Enter a number:");
      string input1 = Console.ReadLine();
      Console.WriteLine("Enter another number:");
      string input2 = Console.ReadLine();

      if (int.TryParse(input1, out int num1) && int.TryParse(input2, out int num2))
      {
        Console.WriteLine("The sum of those numbers is:");
        Console.WriteLine(num1 + num2);
      }
      else
      {
        Console.WriteLine("请输入有效的整数!");
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:25:18