结对编程作业:四则运算设计
一、算法设计思路:
设计思路
- 主程序模块
初始化与交互控制:
使用 srand(time(NULL)) 初始化随机数种子,保证每次运行生成不同题目。通过 while(1) 循环持续接收用户输入,输入 e 退出,否则调用题目生成函数。 - 题目生成模块
随机生成题目:
生成三个 1~20 的随机数(num1, num2, num3)。
随机选择两个运算符(op1, op2)构成表达式(如 num1 op1 num2 op2 num3)。
预处理:
减法:若 num1 < num2,交换两者确保结果非负。
除法:调整 num2 或 num3,确保除数非零且结果可整除。
复合运算符处理:若第二个运算符是减法或除法,需基于第一个运算结果调整后续数值,避免负数或非整除结果。 - 输入输出设计
输入容错:
使用 scanf(" %c", &exitChar) 中的空格跳过空白符(如回车),避免误读输入。 - 正确率计算模块
公式为 (countCorrect / countTotal) * 100,通过浮点运算保留两位小数,避免整数除法精度丢失
二、程序代码
define _CRT_SECURE_NO_WARNINGS
include <stdio.h>
include <stdlib.h>
include <time.h>
void generateQuestion(int* countCorrect, int* countTotal);
float calculateAccuracy(int countCorrect, int countTotal);
int main()
{
srand((unsigned int)time(NULL));
int countCorrect = 0, countTotal = 0;
char exitChar;
while (1) {
printf("输入 'e' 退出或输入任意符号继续...\n");
scanf(" %c", &exitChar);
if (exitChar == 'e') {
break;
}
generateQuestion(&countCorrect, &countTotal);
}
float accuracy = calculateAccuracy(countCorrect, countTotal);
printf("您的正确率为: %.2f%%\n", accuracy);
return 0;
}
void generateQuestion(int* countCorrect, int* countTotal)
{
int num1, num2, num3, result, userAnswer;
char operators[] = { '+', '-', '*', '/' };
char op1, op2;
// 生成三个随机数(范围 1~20)
num1 = rand() % 20 + 1;
num2 = rand() % 20 + 1;
num3 = rand() % 20 + 1;
// 随机选择两个运算符
op1 = operators[rand() % 4];
op2 = operators[rand() % 4];
// 预处理:确保减法结果非负且除法能整除
// 处理第一个运算符
if (op1 == '-') {
// 确保 num1 >= num2
if (num1 < num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
}
if (op1 == '/') {
// 确保能整除且除数不为 0
while (num2 == 0 || num1 % num2 != 0) {
num2 = rand() % 10 + 1;
}
}
// 处理第二个运算符
if (op2 == '-') {
// 根据第一个运算结果调整 num3
int firstResult;
switch (op1) {
case '+': firstResult = num1 + num2; break;
case '-': firstResult = num1 - num2; break;
case '*': firstResult = num1 * num2; break;
case '/': firstResult = num1 / num2; break;
}
// 确保 firstResult >= num3
if (firstResult < num3) {
num3 = rand() % firstResult + 1; // 限制 num3 <= firstResult
}
}
if (op2 == '/') {
// 确保能整除且除数不为 0
while (num3 == 0 || num2 % num3 != 0) {
三、运算结果截图
四、算法设计体会
运算符的合法性处理需细致考虑多种情况。例如,除法预处理中需同时检查除数非零和可整除性;复合运算符(如 (num1 - num2) - num3)需确保每一步结果均合法,避免负数或小数。
调试难点:初始版本在处理第二个运算符时,未正确基于第一个运算结果调整数值(如除法预处理误用 num2 % num3 而非 firstResult % num3),导致部分题目无法生成,需通过逐步调试定位逻辑漏洞。
本次实验我们通过模块化设计和预处理,实现了一个四则运算练习生成程序,尽可能去做到兼顾功能性和用户体验。过程中对运算符处理、随机数调整等问题的解决,深化了我们对程序优化和交互设计的理解。