C语言-文本模式游戏-猜数字的游戏
目录
C语言 文本模式游戏 猜数字的游戏
// 文本模式游戏.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<conio.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <windows.h>
using namespace std;
int main()
{
int answer[4] = {-1};
int guess = 0, times = 0;
int a=0, b=0, i, j;
system("cls");
//以下产生4个不重复的数字(0~9)
for (i = 0; i <= 3; i++) {
srand((unsigned int)time(0)); /*设置种子,并生成伪随机序列*/
answer[i] = rand() % 10;
while(i==0&&answer[i]==0)
answer[i] = rand() % 10;
for (j = 0; j < i; j++)
{
while (answer[i] == answer[j])
{
answer[i]= rand() % 10;
j = -1;//可以重新for j从0开始循环
}
}
}
cout << "请猜数字(四位数,每个位置的数字不重复):" << endl;
while (a != 4)
{
a = 0; b = 0; times++;
do
{
printf_s("\r%d :",times);
cin >> guess;
if (guess == 0) exit(0);
} while (guess < 0 || guess>9999);
for (i = 3; i > -1; i--)
{
for (j = 0; j < 4; j++)
{
if ((int)(guess / pow(10, i)) == answer[j])
{
if (i + j == 3)
a += 1;
else
b += 1;
}
}
guess -= (int)(guess / pow(10, i)) * pow(10, i);
}
printf_s("\n\r %d个位置对%d个位置错\n", a,b);
}
printf_s("\n\r 数字猜对了,按任意键结束");
_getche();
}