制作加减法计算器可以通过多种编程语言实现,以下是几种常见编程语言的实现方法:
1. C语言
```c
include
int main() {
double num1, num2, result;
char operator;
printf("请输入第一个数字: ");
scanf("%lf", &num1);
printf("请输入运算符(+ 或 -): ");
scanf(" %c", &operator); // 注意前面的空格,用于跳过换行符
printf("请输入第二个数字: ");
scanf("%lf", &num2);
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
default:
printf("无效的运算符\n");
return 1;
}
printf("结果: %.2lf\n", result);
return 0;
}
```
2. Python
```python
def simple_calculator(expression):
result = 0
num = 0
sign = 1
for char in expression:
if char.isdigit():
num = num * 10 + int(char)
elif char in ('+', '-'):
result += sign * num
num = 0
sign = 1 if char == '+' else -1
result += sign * num
return result
print(simple_calculator("1+2-3+4")) 输出4
```
3. Java
```java
import java.util.Scanner;
public class CalculatorApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个数字:");
double num1 = scanner.nextDouble();
System.out.println("请输入运算符(+ 或 -):");
char operator = scanner.next().charAt(0);
System.out.println("请输入第二个数字:");
double num2 = scanner.nextDouble();
double result;
if (operator == '+') {
result = num1 + num2;
} else if (operator == '-') {
result = num1 - num2;
} else {
System.out.println("无效的运算符");
return;
}
System.out.println("结果: " + result);
}
}
```
4. JavaScript
```javascript
function simpleCalculator(expression) {
let result = 0;
let num = 0;
let sign = 1;
for (let char of expression) {
if (!isNaN(char)) {
num = num * 10 + parseInt(char);
} else if (char === '+' || char === '-') {
result += sign * num;
num = 0;
sign = char === '+' ? 1 : -1;
}
}
result += sign * num;
return result;
}
console.log(simpleCalculator("1+2-3+4")); // 输出4
```
5. C++