现代软件工程 第一章概论习题第1题 李艳薇

实现自动出题功能:

程序并没有实现全部要求,后续将会继续改进。

  实现结果:

程序代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <time.h>

using namespace std;

#define N 100


bool createProblem()
{
int i,op,x;
char st[100];
int dt[100];
int ct[2];
memset(dt,-1,sizeof(dt));
i=0;
ct[0]=ct[1]=0;

op=rand()%7;
if(op==0) {
st[i++]='(';
ct[op]++;
}
dt[i++]=rand()%N;

int count=0;
while(count<100)
{
op=rand()%7;
if(op==6)
{
st[i++]='=';
if(ct[0]!=ct[1]) {
return false;
}
break;
}
else if(op==0 || op==1)
{
if(op==0) {
if(dt[i-1]==-1&&st[i-1]!=')') { // '('前没有整数,即'('前是个运算符号或者是'('
st[i++]='(';
ct[op]++;
} else {
return false;
}
} else if(op==1&&ct[0]>ct[1]) {
if(dt[i-1]!=-1 || st[i-1]=='(') {
st[i++]=')';
ct[op]++;
} else {
return false;
}
}
}
else
{
if(dt[i-1]!=-1||st[i-1]=='(') {
if(op==2) {
st[i++]='+';
} else if(op==3) {
st[i++]='-';
} else if(op==4) {
st[i++]='*';
} else if(op==5){
st[i++]='/'; //除数为0的情况暂时不判断
} else {
return false;
}

x=rand()%N;
int m=N/5;
while(x<=m) {
st[i++]='(';
ct[0]++;
x=rand()%N;
}

dt[i++]=rand()%N;
}


}

count++;

}

if(count==100) {
return false;
}

int n=i;
st[n]='?';
for(i=0;i<=n;i++)
{
if(dt[i]==-1) {
cout<<st[i];
} else {
cout<<dt[i];
}
}
return true;
}


int main()
{
int i;
srand(time(NULL));
//srand((unsigned)time(NULL));

for(i=1;i<=20;i++)
{
while(1) {
if(createProblem()) {
cout<<endl;
break;
}
}
}
return 0;
}

 

posted @ 2016-09-12 12:53  yigebokeyuan  阅读(212)  评论(0编辑  收藏  举报