2014-10-05 132 views
1

因此,我的代碼使用C有問題。還沒有學習如何使用do/while命令。我永遠無法看到最終的結果是正確的。 我試着編碼顯示隨機(9例如) 我按9並說太低。然後在最後,隨機數表示爲14. 我不確定在整個用戶的輸入嘗試中如何使隨機數保持一致。猜測遊戲幫助需要隨機數

// This is a guessing game. You have 4 attempts to guess the number between 1-20. 
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int main(){ 

    int usersInput; 
    int range; 
    range = rand() %21; 

    printf("Hello and welcome to my game! I have a number in my head between 1-20.\n"); 
    printf("Try and guess what it is.\n"); 
    printf("Please enter your guess as an integer.\n"); 
    scanf("%d", &usersInput); 
// These are the cases for your first attempted 
// Attempt 1 
    if (usersInput > range) { 
     printf("Your guess is too high. Please try again\n"); 
    } 
    else if (usersInput < range){ 
     printf("Your guess is too low. Please try again\n"); 
    } 
    else if (usersInput == range){ 
     printf("You are correct! Congratulations, you win!!\n"); 
    return 0; 
    } 
// Attempt 2   
    scanf("%d", &usersInput); 
    if (usersInput > range){ 
     printf("Your guess is too high. Please try again\n"); 
    } 
    else if(usersInput < range){ 
     printf("Your guess is too low. Please try again\n"); 
    } 
    else if(usersInput == range){ 
     printf("You are correct! Congratulations, you win!!\n"); 
    return 0; 
    } 
// Attempt 3 
    scanf("%d", &usersInput); 
    if (usersInput > range){ 
     printf("Your guess is too high. Please try again\n"); 
    } 
    else if(usersInput < range){ 
     printf("Your guess is too low. Please try again\n"); 
    } 
    else if(usersInput == range){ 
     printf("You are correct! Congratulations, you win!!\n"); 
    return 0; 
    } 
// Attempt 4 
    scanf("%d", &usersInput); 
    if (usersInput > range){ 
     printf("Your guess is too high. You lose!\n"); 
     printf("the random number is %d \n", rand() %21); 
    } 
    else if(usersInput < range){ 
     printf("Your guess is too low. You Lose!\n"); 
     printf("the random number is %d \n", rand() %21); 
    } 
    else if(usersInput == range){ 
     printf("You are correct! Congratulations, you win!!\n"); 
     printf("the random number is %d \n", rand() %21); 
     return 0; 
    } 
} 
+1

不錯的選擇在用戶名的方式:) – Krease 2014-10-05 16:57:51

回答

3

的問題是純粹的輸出在最後 - 你輸出的rand(),而不是你在一開始確定的值range結果:

printf("the random number is %d \n", rand() %21); 

應該

printf("the random number is %d \n", range); 
+0

我總是得到11作爲隨機數 – Chris 2014-10-05 16:51:31

+0

嘗試在調用之前初始化隨機種子: 'srand(time(NULL));' - 查看[這個相關的問題](http://stackoverflow.com/questions/21273550/in-c-how-does-srand-relate-to-rand-function)瞭解詳情爲什麼。 – Krease 2014-10-05 16:53:49

+1

+1對__Chris__,回答__Chris__和一些有價值的見解offcourse :-) – 2014-10-05 17:21:10