您的位置:首页 > 编程语言

结对编程 四则运算

2015-10-18 14:07 501 查看
一、需求分析:

设计一个可以进行加减乘除运算法的一个小程序 产生0~10之间的随机整数 当用户输入+号表示选择加法、输入-号表示选择减法 、 输入*号表示选择乘法 、 输入/号表示选择除法 、输入00表示结束程序 结束时统计计算结果。


二、设计思路:

1、定义 Calculation_formula();产生随机生成运算式;

2、定义 number是总的测试题数,accepted是正确题数;

3、 定义 temp随机生成0-3表示相应运算符;

三、具体实现

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>

int right;

void Menu();//菜单说明
void Calculation_formula();//随机生成运算式
void swap(int *a,int *b);//交换数值
void reverse(char str[],int n);//数组逆转

int main()
{
int number=0,accepted=0;
//number是总的测试题数,accepted是正确题数
int i,length,true_result;
char result[5];
Menu();
while(1){
i=0;
true_result=0;
Calculation_formula();
scanf("%s",result);//以数字字符数组形式保存输入的结果
if(result[1]=='0'&&result[0]=='0')//结束标志
break;
length=strlen(result);
reverse(result,length);
while(result[i]!='\0'){//将数字字符串转换成对应数值
true_result+=(result[i]-48)*pow(10,i);
i++;
}
if(true_result==right){
accepted++;
printf("计算正确!\n");
}
else{
printf("计算错误!正确结果是:%d\n",right);
}
number++;
fflush(stdin);
}
printf("测试结束!\n共%d道题目,通过%d道!\n",number,accepted);
return 0;
}

void Menu()//菜单说明
{
printf("\n\n");
printf("\t ---------程序说明----------\n");
printf("\t|    输入+号表示选择加法    |\n");
printf("\t|    输入-号表示选择减法    |\n");
printf("\t|    输入*号表示选择乘法    |\n");
printf("\t|    输入/号表示选择除法    |\n");
printf("\t|    输入00表示结束程序     |\n");
printf("\t ---------------------------\n");
printf("测试开始:\n");
}

void Calculation_formula()//运算式生成
{
int temp1,temp2;//保存随机生成的运算数
char c;//保存运算符
int temp;//随机生成0-3表示相应运算符
srand((unsigned)time(NULL));//将当前时间设为随机函数种子
temp=rand()%4;
temp1=rand()%10;
temp2=rand()%10;
switch (temp){
case 0://加法
c='+';
right=temp1+temp2;
break;
case 1://减法
c='-';
if(temp1<temp2)//结果非负
swap(&temp1,&temp2);
right=temp1-temp2;
break;
case 2://乘法
c='*';
right=temp1*temp2;
break;
case 3://除法
c='/';
if(temp1==0&&temp2==0){//两运算数不能都是0
do{
temp1=rand()%10;
temp2=rand()%10;
}while(temp1||temp2);
}
if(temp1<temp2)//被除数应不小于除数
swap(&temp1,&temp2);
if(temp2==0||temp1%temp2){//除数不能是0且相除不能有余数
do{
temp2=rand()%10;
}while(!temp2||(temp1%temp2));
}
right=temp1/temp2;
break;
}
printf("%d%c%d=",temp1,c,temp2);
}

void swap(int *a,int *b)//交换数值
{
int p=*a;
*a=*b;
*b=p;
}

void reverse(char str[],int n)//将数组逆转
{
char c;
int i;
for(i=0;i<n/2;i++){
c=str[i];
str[i]=str[n-i-1];
str[n-i-1]=c;
}
}


 四:测试结果及截图



五、psp耗时表:



六、总结:在结对编程的过程中因为我和我的搭档王祥想法不一样,往往造成进行不下去,历经了一次一次失败最终结果自我认为还可以吧

总之结对编程这次忘我懂得了一个道理 ;要学会倾听别人的想法;也学到一些事情。还是有收获的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: