I am a beginner in C programming and I want some help with a right digit counter in a number guess game. In this game, a random secret number of 4 digits is generated and user has to guess it by entering different numbers. In this code, each digit of the user input is scanned and checked. If a digit of the secret number is found in input, the counter k adds 1 and so it should give number of guessed digits. Order is not important (at this stage). Problem: the game gives a smaller number of digits guessed.
#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;
}
Example of output:
Enter a number:2015 number of guessed digits is 2 secret number =4901
Enter a new number:4902 number of guessed digits is 2 secret number =4901
Enter a new number:4901 number of guessed digits is 3 secret number =4901
Enter a new number:
Thanks for help in advance!
Aucun commentaire:
Enregistrer un commentaire