结对编程——随机生成四则运算程序

在本次结对编程中,我和2152634王锴中同学一同进行参与了随机生成四则运算题目程序的编写,本次编写环境在clion上,使用c++风格的代码完成编写。在编写的过程中,我们一同探讨了用哪种语言进行编译,最终选定c++,原因在于对c++的掌握程度更深。在一起完成此项目的同时,我们收获了很多,尤其对方的一些编译技巧,我们在互相学习与补充,增进对c++的理解。以下是程序的源代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <tuple>
// Function to check whether given answer is correct
bool check_answer(int num1, int num2, char op, int ans) {
int correct_ans = (op == '+') ? (num1 + num2) : (num1 - num2);
return ans == correct_ans;
}

// Function to generate unique arithmetic problems
std::vector<std::tuple<int, int, char>> generate_arithmetic_problems(int total_problems) {
srand((unsigned)time(NULL));
int min = 0, max = 100;
int count = 1;

std::vector<std::tuple<int, int, char>> problems;

while (count <= total_problems) {
int num1 = rand() % (max - min + 1) + min;
int num2 = rand() % (max - min + 1) + min;
char operation = (rand() % 2 == 0) ? '+' : '-';

problems.push_back(std::make_tuple(num1, num2, operation));
count++;
}

return problems;
}

int main() {
int total_problems = 300;
auto problems = generate_arithmetic_problems(total_problems);

std::cout << "=== Arithmetic Practice Problems ===" << std::endl;
for (int i = 0; i < total_problems; i++) {
std::cout << "Problem " << i + 1 << ": "
<< std::get<0>(problems[i]) << " "
<< std::get<2>(problems[i]) << " "
<< std::get<1>(problems[i]) << " = ?" << std::endl;
}

std::cout << "===Enter your answers===" << std::endl;
std::vector<int> user_answers;
for (int i = 0; i < total_problems; i++) {
int answer;
std::cin >> answer;
user_answers.push_back(answer);
}

std::cout << "===Results===" << std::endl;

for (int i = 0; i < total_problems; i++) {
int num1 = std::get<0>(problems[i]);
int num2 = std::get<1>(problems[i]);
char operation = std::get<2>(problems[i]);
int user_ans = user_answers[i];

if (check_answer(num1, num2, operation, user_ans)) {
std::cout << "Problem " << i + 1 << ": Correct!" << std::endl;
} else {
std::cout << "Problem " << i + 1 << ": Incorrect." << std::endl;
}
}

return 0;
}

 

posted @   铁匠JJJJ  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示