【问题标题】:calling scanf inside do while loop is breaking the loop在 do while 循环中调用 scanf 正在打破循环
【发布时间】:2021-11-23 12:53:18
【问题描述】:

我有一个do while 循环。当我在没有scanf() 的情况下运行它时,它运行正常。但是,如果我输入 scanf() 它会打破循环!为什么???

代码:

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
> 

但是当我在没有 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!!
> 

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

【问题讨论】:

  • 如果可能,请使用现代 C 编译器!我说warning: format specifies type 'int *' but the argument has type 'int',这是你的主要问题。

标签: c while-loop scanf c89


【解决方案1】:

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

scanf("%d", &guessed);

scanf 工作原理的解释可见here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多