CExercise_05_1函数_3交互式简易计算器
题目:
交互式简易计算器-函数/全局变量
Gn!
实现一个终端交互式的简易计算器,交互的形式大体如下:
要求至少提供四种运算加减乘除,如下: 并且在结束进程时,打印总共执行操作的次数。(也就是这些函数调用的次数)
注意:除法的实现,要求判断除数不为0,并且在除数为0时使用exit表示异常退出进程。
细节scanf的输入%c前需要加空格,以确保正确读到字符.
分析:
:
代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h> //exit() 是 <stdlib.h> 提供的函数,用于终止程序运行。
// 全局变量,用于记录操作次数
int operation_count = 0;
// 函数声明
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
void print_operation_count();//打印操作次数
int main() {
int a, b;
char operator;
char choice;
do {
printf("请输入要计算的表达式(例如,5 + 3): ");
scanf(" %d %c %d", &a, &operator, &b);
switch (operator) {
case '+':
printf("结果: %d\n", add(a, b));
break;
case '-':
printf("结果: %d\n", subtract(a, b));
break;
case '*':
printf("结果: %d\n", multiply(a, b));
break;
case '/':
printf("结果: %.2f\n", divide(a, b));
break;
default:
printf("无效的运算符。\n");
}
// 询问用户是否继续
printf("是否继续? (y/n): ");
scanf(" %c", &choice);
printf("\n");
} while (choice == 'y' || choice == 'Y');
print_operation_count();
return 0;
}
int add(int a, int b) {
operation_count++;
return a + b;
}
int subtract(int a, int b) {
operation_count++;
return a - b;
}
int multiply(int a, int b) {
operation_count++;
return a * b;
}
float divide(int a, int b) {
if (b == 0) {
printf("error:除数为零!\n");
exit(1);
}
operation_count++;
return (float)a / b;
}
void print_operation_count() {
printf("总共执行的操作次数为: %d次\n", operation_count);
}
解决方案总结:
: