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

C语言(12)--简单的10以内四则运算测试器

2015-10-08 21:33 183 查看
随机生成10以内四则运算式,由用户输入计算结果,程序判断对错,输入00结束程序。输出总题数和正确题数。
#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;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: