模拟文曲星上的猜数游戏,先由计算机随机生成一个各位相异的4位数字,由用户来猜,根据用户猜测的结果给出提示:xAyB
其中,A前面的数字表示有几位数字不仅数字猜对了,而且位置也正确,B前面的数字表示有几位数字猜对了,但是位置不正确。
最多允许用户猜的次数由用户从键盘输入。如果猜对,则提示“Congratulations!”;如果在规定次数以内仍然猜不对,则给出提示“Sorry, you haven't guess
the right number!”。程序结束之前,在屏幕上显示这个正确的数字。
验证如下
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main(){
int i,j;
char num[11]="0123456789";
char answer[5]="";
srand((unsigned)time(NULL));
for(i=0;i<4;i++){
while(1){
int r=rand()%10;
if(num[r]!=0){
answer[i]=num[r];
num[r]=0;
break;
}
}
}
int n;
printf("How many times do you want to guess?");
scanf("%d",&n);
for(i=1;i<=n;i++){
char input[5],a=0,b=0;
printf("\nNo.%d of %d times\n",i,n);
printf("Please input 4 different numbers:\n");
scanf("%s",input);
for(j=0;j<4;j++){
if(input[j]==answer[j])a++;
else if(num[input[j]-'0']==0)b++;
}
printf("%dA%dB\n",a,b);
if(a==4){
printf("Congratulations, you got it at No.%d\n",i);
break;
}
}
if(i>n)printf("Sorry, you haven't guess the right number!\n");
printf("Correct answer is:%s\n",answer);
system("pause");
return 0;
}