结对编程——四则运算
本次编程为结对编程,是我与同学2152822刘正耘共同编写。此次编写四则运算代码,虽然看似简单,但是在编写过程中还是遇到了不小的阻碍。本次四则运算需要用到两个运算符,两者在运算时的优先级需要我们进行分辨。我和刘正耘通过多个if-else语句,分多种情况对加减乘除进行优先级判断。同时为了保证能够不断生成算式,我们使用do-while语句,保证了算式能够不断生成。
以下为编程代码:
#include <iostream> #include <cstdlib> #include <ctime> #include <math.h> using namespace std; int main() { srand(time(NULL)); // 初始化随机数种子 float a, b, c; // 用于生成随机数 char op1, op2; // 两个运算符 float ans, userAns; // 答案和用户输入的答案 for (int i = 1; i <= 300; i++) { // 生成两个随机数和两个运算符 a = floor(rand() % 100 + 1); b = floor(rand() % 100 + 1); c = floor(rand() % 100 + 1); do { op1 = rand() % 4 + 42; // 42 是 ASCII 码中的星号 if (op1 == ',')op1 = '/'; op2 = rand() % 4 + 42; if (op2 == ',')op2 = '/'; // 根据运算符优先级生成表达式和答案 if (op1 == '*' || op1 == '/') { if (op2 == '+' || op2 == '-') { ans = (op1 == '*') ? a * b : a / b; ans = (op2 == '+') ? ans + c : ans - c; if (ans > 100 || ans < 0)continue; ans = round(ans * 100); ans = ans / 100; cout << i << ". " << a << op1 << b << op2 << c << " = "; } else { ans = (op1 == '*') ? a * b : a / b; ans = (op2 == '*') ? ans * c : ans / c; if (ans > 100 || ans < 0)continue; ans = round(ans * 100); ans = ans / 100; cout << i << ". " << a << op1 << b << op2 << c << " = "; } } else if (op2 == '*' || op2 == '/') { ans = (op2 == '*') ? b * c : b / c; ans = (op1 == '+') ? a + ans : a - ans; if (ans > 100 || ans < 0)continue; ans = round(ans * 100); ans = ans / 100; cout << i << ". " << a << op1 << b << op2 << c << " = "; } else { ans = (op1 == '+') ? a + b : a - b; ans = (op2 == '+') ? ans + c : ans - c; if (ans > 100 || ans < 0)continue; ans = round(ans * 100); ans = ans / 100; cout << i << ". " << a << op1 << b << op2 << c << " = "; } } while (ans > 100 || ans < 0); cin >> userAns; // 等待用户输入 if (userAns == ans) { cout << "Correct!" << endl << endl; } else { cout << "Incorrect, the answer is " << ans << "." << endl << endl; } } return 0; }
以下为运行结果:

编程体会:
通过这次编程,我明白了人多力量大的道理,在编程中,我和同伴一起努力,解决了许多困难,我们的团队合作是使得程序能够成功运行并且符合要求的必要条件。同时过硬的编程能力也是关键,在这次编程中,我出现了一些低级错误,使得整个编写进度拖慢,今后我要多加练习,使自己的编写更加熟练,在下次表现得更好。

浙公网安备 33010602011771号