2013-11-22 95 views
2

好吧,作爲初學者程序員,我一直負責創建一個簡單的數學測驗程序。它應該提示用戶有多少問題要問,祝賀或告知用戶他們的答案是對還是錯。然後在程序結束時打印出正確的數字和數字不正確。我已經成功完成了所有這些工作,現在我的代碼的唯一問題是它一遍又一遍地提出相同的問題。我在這裏虧本,所以任何幫助將不勝感激,謝謝。簡單的C程序數學測驗

#include <stdio.h> 
    #include <stdlib.h> 
    int main (void) 

    { 
    int i; 
    int response; 
    int correctAnswers = 0; 
    int incorrectAnswers = 0; 

    printf("\nMath Quiz\n"); 
    printf("Please enter # of problems you would wish to try:"); 
    scanf("%d", &response); 

    if(response == 0) 
    { 
     printf("\nThanks for playing!\n"); 
     return 0; 
    } 

    for(i=0; i<response; i++) 
    { 
     int answer = 0; 
     int a = rand() % 12; 
     int b = rand() % 12; 
     printf("\n%d * %d = ",a ,b); 
     scanf("%d", &answer); 
     if((a * b) == answer){ 
      printf("\nCongratulations You are correct!\n"); 
      correctAnswers++; 
     } 
     else{ 
      printf("Sorry you were incorrect!\n"); 
      incorrectAnswers++; 
     } 

    } 
    printf("\n\nYour Results:\n\n\n"); 
    printf("Number Incorrect: %d\n", incorrectAnswers); 
    printf("Number Correct: %d\n", correctAnswers); 
    if(correctAnswers > incorrectAnswers){ 
     printf("You Passed!\nGood work!\n\n"); 
    } 
    else{ 
     printf("You did not pass!\nYou need more work!\n\n"); 
    } 

    return 0; 
} 

此外,格式化的任何批評都是值得歡迎的。謝謝!

+0

通常,保持格式一致是很好的做法。我在這裏做了一些格式化,以便更清楚地說明塊在哪裏開始和結束。程序員可以對格式化樣式相當積極(例如製表符/空格,與/ if等同一行上的大括號),但只要您一致並努力使其可讀,則應該沒問題。 – tjameson

回答

2

您需要了解randon number generator作品C.

rand()如何生成唯一的僞隨機數。這意味着每次運行代碼時,您都會得到完全相同的數字序列

使用srand函數根據源編號生成隨機數。如果您想要經常更改的系統時間,請使用系統時間。

srand(time(NULL));

另外包含頭文件time.h使用time功能。

在調用rand()之前調用該函數。如果您在程序中調用rand()之前沒有調用srand(),就好像調用了srand(1):在程序的每次執行中種子值將爲1,並且生成的序列總是與相同

+0

太棒了,謝謝你們。 – HouseDog

0

使用此srand在你的代碼,這樣的...

int a; 
int b; 

srand(time(0)); 
a = rand() % 12; 
b = rand() % 12; 
+0

太棒了,謝謝。 – HouseDog