C虽然循环编译但没有工作问题

时间:2014-03-02 00:56:35

标签: c if-statement cross-compiling

我仍然掌握着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;
}

1 个答案:

答案 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变量值