2013-06-30 109 views
0

嗨,我知道范围内的随机发生器已经有一个问题,但我不明白。我是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; 
} 

回答

0

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

通过4.操作您测试的1操作价值分配是从兰特值()%4。这意味着操作仅会值为0到3

你do-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; 
+0

我改变了它,但随机发生器不能正常工作。这是如何把一个范围放在随机发生器上? int operation = rand()%4 + 1 – eLg

+0

是的,这将工作。您的代码中还有其他问题。看看你的printf的。你的代码是printf(“什么是%d +%d?”,num1,operation,num2);你有%d +(运营商)%d。但是你指定了三个参数... num1,operator,num2。你应该从这个列表中删除操作符。 –

+0

谢谢..我有一个问题,虽然每当我运行该程序时,它一直显示2 * 8,并且当我输入正确的答案时,它一直显示错误再试一次 – eLg

1

添加到约翰·谢里登的:getch()是一个非标准扩展到C该被许多MS-DOS编译器添加。它通常在<conio.h>中定义。我不知道VS2010是否支持默认。

+0

它的工作原理,谢谢。 – eLg

相关问题