我正在制作一个简单的猜谜游戏程序。用户输入100之外的值,程序会告诉用户他们的猜测是高还是低。我想这样做,程序让用户知道他们之前已经输入了当前的号码。我如何在我的程序中实现一个循环,让用户猜测并将其与数组列表进行比较以查找重复值?
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;
#include <cstdlib>
int main()
{
srand(time(0));
const int SIZE = 100; //array
int number[SIZE];
int i;
int numb = rand() % 100; //rng
cout <<"Hint: "<< numb << endl;
cout << " " << endl;
cout << "I'm thinking of a number between 1 and 100. Guess what it is: ";
for (i = 0; i < SIZE; i++)
{
cin >> number[i];
if (number[i] == numb)
{
cout << "Correct! It's " << numb << endl; //if user guesses correct
break;
}
else if (number[i] < numb) //if user guesses too low
{
cout << "That's too low! guess again: " ;
}
else if (number[i] > numb) //if user guesses too high
{
cout << "That's too high! guess again: " ;
}
}
}
答案 0 :(得分:0)
为已输入的值创建一个向量:
vector <int> atyped;
创建一个检查并返回true或false的函数:
int check(int entered_value, vector <int> atyped) {
ret=0;
for (int i=0;i<atyped.size();i++){
if (enterd_value==atyped[i])
ret=1;
}
return ret;
}
然后你所要做的就是:
if (check(number[i])!=0)
cout << "Sorry, you already tried that one!" <<endl;
希望这至少能让您了解如何解决问题;)
答案 1 :(得分:0)
for (i = 0; i < SIZE; i++)
{
cin >> number[i];
if (number[i] == numb)
{
cout << "Correct! It's " << numb << endl; //if user guesses correct
break;
}
else if (std::find(number, number + i, number[i]) != number + i)
{
cout << "You already guessed that! guess again: " ;
}
else if ... // existing higher or lower
}
指针范围[number, number + i)
是以前的所有猜测。 find
返回第一个匹配指针,如果没有匹配则返回结束(number + i
)。