2014-03-02 39 views
0

我仍然得到C循環的縈繞。我無法弄清楚爲什麼我的while循環不起作用。雖然循環編譯還沒有工作問題

我沒有收到任何錯誤,在這個計劃,但正在發生的事情是,while循環做else if聲明並不會回到if聲明。但是,如果您在第一次猜測時輸入了正確的數字,則會執行if。當您在第一次猜測後的任何時候嘗試猜測時,它將不會在完整的while循環中運行,並始終顯示數字爲「至低」。 我在做什麼錯?我該如何解決它?

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int ranNumGen(); 
void Right(int num); // prompt that you guessed right 
void wrong(int guess, int num); // if else's to tell you to high to low... 
void sorry(int num); // prompt for not guessing it right 


int main(void) 
{ 
    // Local declarations 
    int num; 
    int guess; 
    int a; 

    // Sets variables 
    num = ranNumGen(); 
    a = 0; 


    // Prompt 
    printf("\nLets play a game"); 
    printf("\nCan you guess the number I am thinking of?"); 
    printf("\nI will give you a hint its a number between (1 and 20)"); 
    printf("\nI am also going to going to give you five tries."); 
    printf("\nHave a guess! "); 
    printf("Shows number to win %d", num); // shows number to win to check if it works 
    scanf_s("%d", &guess); 




    while (a < 4) 
    { 
     (a++); 

     if (guess == num) 
     { 
      Right(num); 
      break; 
     } 
     else if (guess < num || guess > num) 
     { 
      wrong(guess, num); 
     } 
    } 


    // End promts 
    if (guess == num) 
    { 
     printf("\nGoodbye\n"); 
    } 
    else 
    { 
     sorry(num); 
    } 
    return 0; 
} 

int ranNumGen() 
{ 
    int range; 
    srand(time(NULL)); 
    range = 20; 
    range = (rand() % range + 10) + 1; 
    return range; 
} 

void Right(int num) 
{ 
    printf("\n\t*******************************************"); 
    printf("\n\t* Wow you guessed it! Yep its %d alright. *", num); 
    printf("\n\t* You won't get it next time! :)  *"); 
    printf("\n\t*******************************************"); 
} 

void wrong(int guess, int num) 
{ 
    if (guess > num) 
    { 
     printf("\nYour guess is to high.", guess); 
     printf("\nTry again: "); 
     scanf_s("%d", &guess); 
    } 
    else if (guess < num) 
    { 
     printf("\nYour guess is to low.", guess); 
     printf("\nTry again: "); 
     scanf_s("%d", &guess); 
    } 
} 

void sorry(int num) 
{ 
    printf("\nSorry buddy, you didn't guess it..."); 
    printf("\nThe number was %d better luck next time.\n", num); 
    return; 
} 
+3

'錯(猜,NUM)的值複製'工作而改變'guess'和'num',並且不能更改這些變量的外部值。 – amdixon

+0

那麼你是否說我需要使用指針?你能告訴我它使用它的樣子嗎?或者指點我一個例子。請? –

回答

1

變化wrong使用指針參數爲guess作爲

void wrong(int *guess, int num) 
{ 
    if ((*guess) > num) 
    { 
     printf("\nYour guess is to high.", *guess); 
     printf("\nTry again: "); 
     scanf_s("%d", guess); 
    } 
    else if ((*guess) < num) 
    { 
     printf("\nYour guess is to low.", *guess); 
     printf("\nTry again: "); 
     scanf_s("%d", guess); 
    } 
} 

這可以讓你的外部guess變量值由wrong