文曲星猜數遊戲

       模擬文曲星上的猜數遊戲,先由計算機隨機生成一個各位相異的4位數字,由用戶來猜,根據用戶猜測的結果給出提示:xAyB。其中,A前面的數字表示有幾位數字不僅數字猜對了,而且位置也正確,B前面的數字表示有幾位數字猜對了,但是位置不正確。

        允許用戶猜的最多次數由用戶從鍵盤輸入。如果猜對,則提示“Congratulation!”;如果在規定的次數以內仍然猜不對,則給出提示“Sorry,you haven't guess the right number!”。程序結束之前,在屏幕上顯示這個正確的數字。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
	int num[4],guess[4];
	int i,j,times;
	int countA,countB;
	int maxTimes;
	times=0;
	printf("How many times do you want to guess?");
	scanf("%d",&maxTimes);
	srand(time(NULL));
	num[0]=rand()%10;
	//隨機生成四個不相同的數字
	for (i=1;i<4;i++)
	{
		do 
		{
			num[i]=rand()%10;
			for (j=0;j<i;j++)
			{
				if (num[i]==num[j])
					break;
			}
		if(j==i)break;
		} while (1);
	}
	//以下注釋部分爲輸出電腦隨機生成的四個數字
	//for (i=0;i<4;i++)
	//{
	//	printf("%d ",num[i]);
	//}
	//printf("\n");

	//以下爲猜數過程
	do 
	{
		countA=0,countB=0;
		times++;
		if (times>maxTimes)
		{
			printf("Sorry,you haven't guess the right number!\n");
			printf("The number is %d%d%d%d.\n",num[0],num[1],num[2],num[3]);
			break;
		}
		for (i=0;i<4;i++)
		{
			scanf("%d",&guess[i]);
		}
		for (i=0;i<4;i++)
		{
			for (j=0;j<4;j++)
			{
				if (guess[j]==num[i])
				{
					if (j==i)
						countA++;
					else
						countB++;
				}
			}
		}
		printf("%d:%dA%dB\n",times,countA,countB);
		if (countA==4)
		{
			printf("Congratulation!\ n");
			break;
		}
	} while (1);
	getch();
}


發佈了58 篇原創文章 · 獲贊 51 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章