在 do while 循环中调用 scanf 会打破循环

calling scanf inside do while loop is breaking the loop

我有一个 do while 循环。当我 运行 它没有 scanf() 时,它 运行 正确。但是如果我输入 scanf() 中断 循环!为什么???

代码:

With scanf()

void main(){
    int num = prng() % 100, guessed, guesses = 0;
    bool  win = false;
    printf("The Game Begins. You Have To Guess A Number\n");
    do{ //A do while loop untill the user guesses the correct number
        printf("Guess a number\n");
        scanf("%d", guessed);
        guesses++;
    }while (!check(guessed, num));
    printf("Yayy!!! You won the game in %d guesses!!", guesses); //Message after guessing the correct number
    return;
}

这会立即打破循环:

> .\a.exe
The Game Begins. You Have To Guess A Number
Guess a number
5
> 

But when I run it without the scanf()

void main(){
    int num = prng() % 100, guessed, guesses = 0;
    bool  win = false;
    printf("The Game Begins. You Have To Guess A Number\n");
    do{ //A do while loop untill the user guesses the correct number
        printf("Guess a number\n");
        guessed = num;
        // scanf("%d", guessed);
        guesses++;
    }while (!check(guessed, num));
    printf("Yayy!!! You won the game in %d guesses!!", guesses); //Message after guessing the correct number
    return;
}

效果很好!!

> .\a.exe
The Game Begins. You Have To Guess A Number
Guess a number
Hurrayyy!!!! You got the number!!!!!!!!!Yayy!!! You won the game in 1 guesses!!
> 

你能解释一下实际问题是什么吗?

您需要在 scanf 函数中的 guessed 变量前面添加 &

scanf("%d", &guessed);

可以查看 scanf 工作原理的解释 here