计算器程序代码可以根据不同的编程语言和需求有多种实现方式。以下是几种常见编程语言的计算器程序代码示例:
Python 示例代码
```python
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
else:
return x / y
while True:
print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'subtract' to subtract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input in ('add', 'subtract', 'multiply', 'divide'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if user_input == 'add':
print(f"The result is: {add(num1, num2)}")
elif user_input == 'subtract':
print(f"The result is: {subtract(num1, num2)}")
elif user_input == 'multiply':
print(f"The result is: {multiply(num1, num2)}")
elif user_input == 'divide':
print(f"The result is: {divide(num1, num2)}")
else:
print("Invalid input!")
```
C 示例代码
```csharp
using System;
class Calculator
{
static void Main()
{
double num1, num2, result;
char operator;
Console.Write("请输入一个运算符 (+, -, *, /): ");
operator = Console.ReadLine();
Console.Write("请输入两个数字: ");
num1 = Convert.ToDouble(Console.ReadLine());
num2 = Convert.ToDouble(Console.ReadLine());
switch (operator)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0.0)
{
result = num1 / num2;
}
else
{
Console.WriteLine("Error: Division by zero is not allowed!");
return;
}
break;
default:
Console.WriteLine("运算符整错了老铁");
return;
}
Console.WriteLine("算出来的结果是: " + result);
}
}
```
Java 示例代码
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2, result;
char operator;
System.out.print("请输入一个运算符 (+, -, *, /): ");
operator = scanner.next().charAt(0);
System.out.print("请输入两个数字: ");
num1 = scanner.nextDouble();
num2 = scanner.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero is not allowed!");
return;
}
break;
default:
System.out.println("运算符整错了老铁");
return;
}
System.out.println("算出来的结果是: " + result);
}
}
```
这些示例代码展示了如何在不同编程语言中实现一个简单的计算器程序,包括基本的加、减、乘、除运算以及异常处理。你可以根据自己的需求选择