随机生成器范围内

时间:2013-06-30 14:50:53

标签: c visual-studio-2010 random getch

嗨我知道范围内的随机发生器已经存在问题,但我不明白。我是C的初学者,我只懂java。在这个程序中,我试图在C中创建一个数学导师。该程序将随机生成1到10的两个数字,以及一个操作符。它运行,但它没有显示下一行,它一直显示不正确的答案。另外,为什么VS2010说getch()未定义?这是代码:

 int ans;
 int ans1;
 int num1 = rand() % 10 + 2;
 int num2 = rand() % 10;
 int operation = rand() % 4;

    printf("\tMATH TUTOR\n");
    if(operation == 1){
        printf("What is %d + %d ?", num1, operation, num2);
        scanf_s("%d",ans1);
        ans = num1 + num2;
        if(ans != ans1){
            printf("Incorrect! Try Again!");
            do{
                scanf_s("%d", &ans1);
            }while( ans != ans);
        }else{
            printf("Correct!");
        }
        }else if(operation == 2){
            printf("What is %d - %d ?", num1, operation, num2);
            scanf_s("%d",&ans1);
            ans = num1 - num2;
            if(ans != ans1){
                printf("Incorrect! Try Again!");
                do{
                    scanf_s("%d", &ans1);
                }while( ans != ans);
            }else{
                printf("Correct!");
                }
        }else if(operation == 3 ){
            printf("What is %d * %d ?", num1, operation, num2);
            scanf_s("%d",&ans1);
            ans = num1 * num2;
            if(ans != ans1){
                printf("Incorrect! Try Again!");
                do{
                    scanf_s("%d", &ans1);
                }while( ans != ans);
            }else{
                printf("Correct!");
            }
            }else if(operation == 4){
                printf("What is %d / %d ?", num1, operation, num2);
                scanf_s("%d",&ans1);
                ans = num1 / num2;
                if(ans != ans1){
                    printf("Incorrect! Try Again!");
                    do{
                        scanf_s("%d", &ans1);
                    }while( ans != ans);
                }else{
                    printf("Correct!");
                }
            }

    getch();
    return 0;
}

2 个答案:

答案 0 :(得分:1)

添加到John Sheridan:getch()是C的非标准扩展,由许多MS-DOS编译器添加。它通常在<conio.h>中定义。我不知道默认情况下VS2010是否支持。

答案 1 :(得分:0)

您的代码存在多个问题,可能会使其与预期的方式不同。

您测试操作值1到4.操作从rand()%4分配它的值。这意味着操作将只有0到3的值。

你做的while循环都有相同的缺陷。他们测试ans!= ans,而你应该测试ans!= ans1。

解决这些问题,你会得到更多。

编辑以提供更好的提示

if(operation == 1){
    printf("What is %d + %d ?", num1, num2);
    scanf_s("%d",ans1);
    ans = num1 + num2;
    if(ans != ans1){
        do{
            printf("Incorrect! Try Again!");
            scanf_s("%d", &ans1);
        }while( ans != ans1);
    }
    printf("Correct!");
}

编辑以显示使用srand

int ans;
int ans1;
srand((unsigned int)time(NULL));  //I've included your (unsigned int) cast.
int num1 = rand() % 10 + 2;
int num2 = rand() % 10;
int operation = rand() % 4;
相关问题