5.11趣味百题7.1猜数
一 问题描述
计算机随机生成一个四位数,请你输入 会给出一定提示 直到正确
二 设计思路
1.利用随机数函数生成一个四位随机数 vc编译需要头文件include<windows.h> 中的rand 随机函数 rand()%x=y;用法为取一个下限为y上限为x+y-1的随机整数
2.利用数组存入 答案与所猜数 利用循环结构进行比较 给出提示
3.答对跳出大循环
三 流程图

四 c++代码实现
#include <iostream>
#include<windows.h>
using namespace std;
int main()
{
int c = 0, t = 0; int x = 0, y = 0; int l = 1000;
int a[4] = { 0 }, b[4] = { 0 }, a1[4] = { 0 };
int shu=0, wei=0;//记录数对与位对
c = rand()%9000+1000;
while (1)
{
shu = 0; wei = 0;
l = 1000;
cout << "请猜一个四位数" << endl;
cin >> t;
if (t == c) { break; }//猜对跳出循环
//a,b存储位数
x = c; y = t;
for (int i = 3; i >= 0; i--)
{
a[i] = x %10;
b[i] = y %10;
x/=10;y/=10;
if (b[i] == a[i]) { wei++; }//记录数对且位对
}
//记录对得数
//拷贝一份答案
for (int i = 0; i < 4; i++)
{
a1[i] = a[i];
}
for (int i = 0; i < 4; i++)
{
if(b[i]==a1[0])
{
a1[0] = 10;
shu++;
}
else if (b[i] == a1[1])
{
a1[1] = 10;
shu++;
}
else if (b[i] == a1[2])
{
a1[2] = 10;
shu++;
}
else if (b[i] == a1[3])
{
a1[3] = 10;
shu++;
}
}
cout << "本次猜对的数个数:" << shu << endl;
cout << "本次猜对的位置数:" << wei << endl;
}
cout << "恭喜你猜对了" << endl;
return 0;
}

浙公网安备 33010602011771号