2013-06-30 103 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

相關問題