我们选择了小学四则运算自动生成程序的作为此次结对编程的任务。如下题目要求:
本次结对编程的过程中和小伙伴的角色分配如下:
驾驶员主要负责代码的编写,领航员引导驾驶员提供思路、修正驾驶员错误等以及对程序的测试工作。
代码内容
头文件引入
#ifndef PCH_H
#define PCH_H
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <vector>
#include <iomanip>
#include <sstream>
#include <fstream>
#endif //PCH_H
类定义
class Calculation {
public:
int quantity; //题目数量
int maximum; //最大数
int elem_len; //每个式子参与运算的个数
bool brackets; //括号
bool decimal; //小数
vector <string> opt{}; //计算符号
vector <string> expression{}; //生成表达式
vector <string> answer{}; //表达式答案
public:
void Create(); //生成表达式
void SetQuantity(int q); //设置题目数量
void SetMaximum(int m); //设置最大数值
void SetBrackets(bool b); //设置是否有括号
void SetDecimal(bool d); //设置是否有小数
void SetElem_len(int len); //设置每个式子中数值的个数
void AddOpt(string op) { //运算符号
this->opt.push_back(op);
}
void SaveFile(); //输出文件
Calculation(int q, int m, bool b, bool d);
};
类实现
Set
前缀方法均为对参数的设置;string
类型vector
变量expression用于保存生成的表达式;Create()
方法用于生成表达式。
void Calculation::Create() {
srand((unsigned int)(time(NULL)));
for (int x = 0; x < quantity; x++) {
string tmp;
int left = rand() % (elem_len - 1); // 括号左位置
int right = rand() % (elem_len - left - 1) + left + 1; //括号右位置
while (left == 0 && right == elem_len - 1) {
left = rand() % (elem_len - 1); // 括号左位置
right = rand() % (elem_len - left - 1) + left + 1; //括号右位置
}
for (int i = 0; i < elem_len; i++) {
string temp = "";
float number = rand() % maximum + 1 + (float)(rand() % maximum) / maximum;
if (this->decimal) { //小数
temp = roundAny(number, 2);
}
else {
temp = roundAny(number, 0);
}
if (brackets) { //括号
if (i == left) {
temp = "(" + temp + " ";
}
else if (i == right) {
temp = temp + ")";
}
else {
temp = temp + " ";
}
}
else {
temp = temp + " ";
}
if (temp.size() == 2) {
temp = " " + temp;
}
else if (temp.size() == 3) {
temp = " " + temp;
}
tmp += temp;
if (i < elem_len - 1)
tmp += opt[rand() % (opt.size())] + " ";
else
tmp += " = ";
}
expression.push_back(tmp);
//std::cout << expression[x] << endl;
}
}
剩余部分方法实现
?
补充函数
static std::string roundAny(float r, int precision) {
std::stringstream buffer;
buffer << std::fixed << std::setprecision(precision) << r;
return buffer.str();
}
此函数用于将浮点型数据转换成特定位小数的字符串。
项目完成的结果:
常规输入输出
输出文件
原文:https://www.cnblogs.com/leexin/p/10800890.html