【发布时间】:2016-05-14 12:12:01
【问题描述】:
我是 C 编程的初学者,我希望在猜数游戏中获得正确的数字计数器方面的帮助。在这个游戏中,随机生成一个 4 位的秘密数字,用户必须通过输入不同的数字来猜测它。在此代码中,用户输入的每个数字都被扫描和检查。如果在输入中找到秘密数字的数字,则计数器 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 密码=4901
输入一个新号码:4902 猜到的位数是 2 密码=4901
输入一个新号码:4901 猜到的位数是 3 密码=4901
输入一个新号码:
提前感谢您的帮助!
【问题讨论】:
-
逻辑似乎很少有问题。只是为了让您走上正确的轨道。1) else if 只有在前一个条件为假时才检查条件。 2) 可以一次性输入整个 4 位数字,然后将其拆分为 4 位数字,在循环中分别检查每个数字与四个随机生成的数字并在每次匹配时递增计数器。希望这会有所帮助。
-
谢谢!问题似乎出在 scanf() - 它扫描了第一个字符,而 getchar() 只扫描了剩下的 3 个字符。这里有更多细节cboard.cprogramming.com/c-programming/…
标签: c random while-loop do-while