写一段C#语言计算器代码
时间: 2023-08-03 12:24:34 浏览: 53
好的,以下是一个简单的 C# 语言计算器代码:
```
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
double num1, num2, result;
char operator;
Console.WriteLine("Enter first number:");
num1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter second number:");
num2 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter operator (+, -, *, /):");
operator = char.Parse(Console.ReadLine());
switch (operator)
{
case '+':
result = num1 + num2;
Console.WriteLine("Result: " + result);
break;
case '-':
result = num1 - num2;
Console.WriteLine("Result: " + result);
break;
case '*':
result = num1 * num2;
Console.WriteLine("Result: " + result);
break;
case '/':
if (num2 != 0)
{
result = num1 / num2;
Console.WriteLine("Result: " + result);
}
else
{
Console.WriteLine("Error: Cannot divide by zero.");
}
break;
default:
Console.WriteLine("Error: Invalid operator.");
break;
}
Console.ReadLine();
}
}
}
```
这个计算器程序会要求用户输入两个数字和一个运算符,然后根据运算符计算结果并输出。在代码中,我们使用了 switch 语句来根据不同的运算符进行不同的计算。同时,我们也加入了对除数为零的处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)