编写一个小型计算器。
时间: 2024-01-11 08:18:31 浏览: 35
好的,以下是一个简单的计算器的 Python 代码:
```python
while True:
try:
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
operator = input("请选择运算符(+、-、*、/):")
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
else:
print("输入有误,请重新输入!")
except ValueError:
print("输入有误,请重新输入!")
```
相关问题
用fortran语言编写一个小型计算器程序,用键盘输入两个数字,再根据运算符号判断这两个数字做加减乘除的哪一项运算,每做完一次运算后,让用户来决定是否还要进行新的运算
以下是用 Fortran 语言编写的一个小型计算器程序的示例代码:
program calculator
implicit none
character(len=1) :: operator
real :: num1, num2, result
do
write(*,'(a)',advance='no') "请输入第一个数字: "
read(*,*) num1
write(*,'(a)',advance='no') "请输入运算符号 (+, -, *, /): "
read(*,*) operator
write(*,'(a)',advance='no') "请输入第二个数字: "
read(*,*) num2
if (operator .eq. "+") then
result = num1 + num2
else if (operator .eq. "-") then
result = num1 - num2
else if (operator .eq. "*") then
result = num1 * num2
else if (operator .eq. "/") then
result = num1 / num2
else
write(*,*) "无效的运算符号"
end if
write(*,'(a,f0.2)') "结果是: ", result
write(*,'(a)',advance='no') "是否继续进行运算 (y/n)? "
read(*,*) operator
end do
end program calculator
程序的工作流程是:
1. 使用 `do` 循环来控制运算的次数。
2. 使用 `write` 和 `read` 语句读入两个数字和运算符号。
3. 使用 `if` 语句根据运算符号判断这两个数字做加减乘除的哪一项运算。
4. 使用 `write` 语句输出运算结果。
5. 使用 `write` 和 `read` 语句询问用户是否继续进行新的运算。
如果用户输入的是 "y",则继续循环;如果输入的是 "n",则退出循环并结束程序。
用C语言编写一个可以实现两个数加减乘除运算的小型计算器
好的,以下是一个可以实现两个数加减乘除运算的小型计算器的 C 语言代码:
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("请输入运算符 (+, -, *, /): ");
scanf("%c", &operator);
printf("请输入两个数字: ");
scanf("%lf %lf", &num1, &num2);
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
printf("错误的运算符");
return 1;
}
printf("%.2lf %c %.2lf = %.2lf", num1, operator, num2, result);
return 0;
}
希望这个代码对你有所帮助!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)