c - 使用 while 和 do-while 循环在 C 中输出简单的猜数游戏

标签 c random while-loop do-while

我是 C 编程初学者,我需要一些有关猜数字游戏中正确数字计数器的帮助。在这个游戏中,会生成一个 4 位数字的随机 secret 数字,用户必须通过输入不同的数字来猜测它。在此代码中,将扫描并检查用户输入的每个数字。如果在输入中找到 secret 数字的数字,则计数器 k 加 1,因此它应该给出猜测的数字数。顺序并不重要(在这个阶段)。问题:游戏给出的猜测位数较少。

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

int main(){
setvbuf(stdout,NULL,_IONBF,0);

int n=10000;
srand(time(NULL));
int r=rand()%n;//makes a random (secret) number

int d1,d2,d3,d4;//declares digits of the random number

d1=r/1000;//these 4 lines calculate separate digits of the random number
d2=(r-d1*1000)/100;
d3=(r-d1*1000-d2*100)/10;
d4=r-d1*1000-d2*100-d3*10;

char c;//declares char c which will be a digit of a number given by user (guess)

if(d1!=d2&&d1!=d3&&d1!=d4&&d2!=d3&&d2!=d4&&d3!=d4){//prevents using a random number which has some duplicate digits

 printf("Enter a number:");
 scanf("%c",&c);//scan first digit(character) of user's guess

 while(c!='\n'){//scan all digits(characters) of user's guess until new line
 int k=0;//initialize a counter of right guesses

 while(c!='\n'){//scan all digits(characters) of user's guess until new line
  c=getchar();//scan each character of a user's number
  int digit=c-48;//convert the character into digit by using its ASCII value

   if(digit==d1){//if user digit coincides with the first digit of random number add 1 to counter
    ++k;
   }
   else if(digit==d2){//if no, check if it coincides with second digit
    ++k;
    }
   else if(digit==d3){
    ++k;
   }
   else if(digit==d4){
    ++k;
   }

  }

 printf("number of guessed digits is %i\n",k);
 printf("secret number =%i\n\n",r);

 printf("Enter a new number:");//asks the user to try another number
 scanf("%c",&c);//scan new digit
 }
}

return 0;

}

输出示例:

输入数字:2015 猜中的位数是2 secret 号码=4901

输入新号码:4902 猜中的位数是2 secret 号码=4901

输入新号码:4901 猜中的位数为 3 secret 号码=4901

输入新号码:

提前感谢您的帮助!

最佳答案

由于您在 scanf() 之后立即使用 getchar() 而不检查 scanf() 的结果,因此您总是会丢失第一个数字.
移动

c=getchar();

在 if 条件之后。

关于c - 使用 while 和 do-while 循环在 C 中输出简单的猜数游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35208532/

相关文章:

c++ - 当通过 C/C++ 中的 double 传输时,是否保证保留 float ?

c - 随机数发生器产生相同的随机数

java - 如何构造 JNI 调用以避免内存泄漏?

javascript - GIF 随机变化

python - 替换 Python 中的深度循环

c - FreeRTOS 在调度程序启动之前(或停止之后)排队等待 IO

javascript - 将多个 .random 类添加到多个 div 而不会重复

python - randomstate在Numpy中与seed相关的使用

java - 需要帮助修改输入验证和错误消息的代码

java - While 循环无法正常工作