用简易计算器怎么编程序

时间:2025-01-28 00:26:57 网络游戏

使用简易计算器进行编程,可以选择不同的编程语言来实现。以下是几种常见编程语言的简易计算器程序示例:

1. C语言

```c

include

int add(int a, int b) {

return a + b;

}

int sub(int a, int b) {

return a - b;

}

int multi(int a, int b) {

return a * b;

}

double divide(int a, int b) {

return (double)a / b;

}

int main() {

int choice, oper1, oper2, result;

printf("-------简易计算器------\n");

printf("1. 加法 2. 减法\n");

printf("3. 乘法 4. 除法\n");

printf("5. 退出系统\n");

while (1) {

printf("请输入选择的运算:\n");

scanf("%d", &choice);

if (choice >= 1 && choice <= 4) {

printf("请输入两个数字:\n");

scanf("%d %d", &oper1, &oper2);

switch (choice) {

case 1:

result = add(oper1, oper2);

break;

case 2:

result = sub(oper1, oper2);

break;

case 3:

result = multi(oper1, oper2);

break;

case 4:

if (oper2 != 0) {

result = divide(oper1, oper2);

} else {

printf("错误:除数不能为零!\n");

continue;

}

break;

}

printf("%d %c %d = %d\n", oper1, choice == 4 ? '/' : '+', oper2, result);

} else if (choice == 5) {

break;

} else {

printf("无效的选择,请重新输入。\n");

}

}

return 0;

}

```

2. C++

```cpp

include

using namespace std;

double add(double a, double b) {

return a + b;

}

double sub(double a, double b) {

return a - b;

}

double multi(double a, double b) {

return a * b;

}

double divide(double a, double b) {

return a / b;

}

int main() {

int choice;

double num1, num2, result;

cout << "-------简易计算器------" << endl;

cout << "1. 加法 2. 减法" << endl;

cout << "3. 乘法 4. 除法" << endl;

cout << "5. 退出系统" << endl;

while (1) {

cout << "请输入选择的运算:" << endl;

cin >> choice;

if (choice >= 1 && choice <= 4) {

cout << "请输入两个数字:" << endl;

cin >> num1 >> num2;

switch (choice) {

case 1:

result = add(num1, num2);

break;

case 2:

result = sub(num1, num2);

break;

case 3:

result = multi(num1, num2);

break;

case 4:

if (num2 != 0) {

result = divide(num1, num2);

} else {

cout << "错误:除数不能为零!" << endl;

continue;

}

break;

}

cout << num1 << " " << (choice == 4 ? '/' : '+') << " " << num2 << " = " << result << endl;

} else if (choice == 5) {

break;

} else {

cout << "无效的选择,请重新输入。" << endl;

}

}

return 0;

}

```

3. Python