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

C#简易计算器代码报错:Visual Studio提示if语句后大括号存在错误

解决C#简易计算器的if语句编译错误

你的问题出在每个if和else if语句末尾的分号;,这是导致Visual Studio报错的直接原因:

  • 在C#语法中,分号;代表空语句。当你在if (oper == "+");后加了分号,相当于告诉编译器这个if的执行体是空的,后续的{}代码块就变成了和if无关的独立代码块。
  • 这种情况下,else和else if找不到对应的if语句,编译器就会在大括号位置抛出错误。

修正后的代码

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace calculator_c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //Calculator inputs
            Console.WriteLine("Enter the first integer.");
            int int1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the second integer.");
            int int2 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter operation.");
            string oper = Console.ReadLine();

            //Calculator solving
            if (oper == "+")
            {
                int ans = int1 + int2;
                Console.WriteLine("Answer = " + ans);
            }
            else if (oper == "-")
            {
                int ans = int1 - int2;
                Console.WriteLine("Answer = " + ans);
            }
            else if (oper == "*")
            {
                int ans = int1 * int2;
                Console.WriteLine("Answer = " + ans);
            }
            else if (oper == "/")
            {
                int ans = int1 / int2;
                Console.WriteLine("Answer = " + ans);
            }
            else
            {
                Console.WriteLine("Error.");
            }
        }
    }
}

额外提示:可以添加输入合法性校验,比如用户输入非整数时的异常处理、除法时除数为0的判断,避免程序运行时崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:45:48