Here's a simple C# calculator code example that demonstrates basic arithmetic operations:

using System;

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            double num1, num2, result;
            char op;

            Console.WriteLine('Enter first number: ');
            num1 = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine('Enter operator (+, -, *, /): ');
            op = Convert.ToChar(Console.ReadLine());

            Console.WriteLine('Enter second number: ');
            num2 = Convert.ToDouble(Console.ReadLine());

            switch (op)
            {
                case '+':
                    result = num1 + num2;
                    Console.WriteLine(num1 + ' + ' + num2 + ' = ' + result);
                    break;
                case '-':
                    result = num1 - num2;
                    Console.WriteLine(num1 + ' - ' + num2 + ' = ' + result);
                    break;
                case '*':
                    result = num1 * num2;
                    Console.WriteLine(num1 + ' * ' + num2 + ' = ' + result);
                    break;
                case '/':
                    if (num2 == 0)
                    {
                        Console.WriteLine('Cannot divide by zero');
                    }
                    else
                    {
                        result = num1 / num2;
                        Console.WriteLine(num1 + ' / ' + num2 + ' = ' + result);
                    }
                    break;
                default:
                    Console.WriteLine('Invalid operator');
                    break;
            }

            Console.ReadLine();
        }
    }
}

This program prompts the user to enter two numbers and an operator. It then performs the corresponding operation based on the operator and outputs the result to the console. The program supports addition, subtraction, multiplication, and division operations. However, in the case of division, it avoids division by zero.

C# Calculator Code Example: Simple Arithmetic Operations

原文地址: https://www.cveoy.top/t/topic/nENc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录