【问题标题】:How to fix the issue of scanning repeatedly in this program? [duplicate]如何解决此程序中重复扫描的问题? [复制]
【发布时间】:2017-07-22 09:56:29
【问题描述】:

所以这个程序应该猜一个你在脑海中想到的数字。但是如果你运行它并在问你第一个问题后看到它不再需要输入。

#include <stdio.h>
#include <stdlib.h>

int main(){
printf("Enter the upper limit for the range of numbers:\n");
int n;
scanf("%d", &n);
int low=0;
int high=n;
printf("Answers should only be y for yes or n for no.\n");
do{
    int median;
    median=(high+low)/2;
    printf("Is your number greater than %d median?\n", median);
    char ans;
    scanf("%c", &ans);
    if(ans=='y' || ans=='Y'){
        low=median;
        continue;
    }
    else{
        printf("Is your number smaller than %d median?\n", median);
        scanf("%c", &ans);
        if(ans=='y' || ans=='Y'){
            high = median;
            continue;
        }
        else
        {
           low = high = median;
        }
        }
}while(low != high);
printf("Your number is: %d\n", low);
return 0;

}

【问题讨论】:

  • 那我该如何解决呢?
  • 这个问题有 10 个 (!) 答案。
  • 正如 Eugene Sh 所说,您可以在 stackoverflow 本身上找到很多问题的答案。但是,如果您仍然想在现有代码中修复它,请使用 scanf("%*c%c", &ans);看看:stackoverflow.com/questions/1669821/…

标签: c


【解决方案1】:

试试这个:

scanf(" %c", &ans);

而不是

scanf("%c", &ans);

【讨论】:

  • 谢谢你这工作。但这背后的逻辑是什么。
【解决方案2】:

我认为您正在寻找一个猜数字的程序,但您的代码似乎不是最佳方式。可以在一个循环和三个 if-else 语句中完成:如果匹配打印“恭喜”并打破循环,否则寻找更改上限或下限。

试试这样的:

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

int main(void) 
{

int random_num = 0;
int guessed_num = 0;
int counter = 0; 
int lower = 0;
int upper;    

printf("Enter the upper range: ");
scanf("%d", upper);

srand(time(NULL));
random_num = rand() % upper + 1;

printf("Guess my number! "); 

    while(1)
    {
        counter++; 

        scanf("%d", &guessed_num);

        if (guessed_num == random_num) 
        {
            printf("You guessed correctly in %d tries! Congratulations!\n", counter); 
            break;
        }

        if (guessed_num < random_num) 
            printf("Your guess is too low. Guess again. ");

        if (guessed_num > random_num) 
            printf("Your guess is too high. Guess again. ");

    } 

return 0;   
}

如果您想坚持自己的代码,我建议您使用getchar() 函数而不是scanf("%c", &amp;ans)。你可以从这个link了解更多信息

【讨论】:

  • 我按照链接中的示例进行了尝试,但没有成功。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 2013-10-28
  • 1970-01-01
  • 2021-09-24
  • 2015-10-02
相关资源
最近更新 更多