【问题标题】:How to search an array for an int value that has already been entered previously如何在数组中搜索先前已输入的 int 值
【发布时间】:2018-05-24 12:29:27
【问题描述】:

我正在制作一个简单的猜谜游戏程序。用户输入一个 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: " ;
      }           
  }
}

【问题讨论】:

  • 将所有以前输入的值保存在 std::set 中,并在获得新值时检查它是否以前输入过
  • 不要直接将数字添加到数组中。将其保存在临时变量中,遍历数字数组以检查重复项,仅在未找到重复项时添加。不要接受数字数组中超出可接受范围的值。在这种情况下,100。仅当您不应该使用 STL 时才这样做。

标签: c++ arrays loops


【解决方案1】:

为已输入的值创建一个向量:

vector <int> atyped;

创建一个函数来检查并返回真假:

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;

希望这至少可以让您了解如何解决您的问题;)

【讨论】:

  • 感谢您的帮助。我唯一的问题是我还没有在课堂上学习矢量。你知道我可以用循环和数组来做到这一点吗?谢谢
  • std::find 可用于检查元素。 cplusplus.com/reference/algorithm/find
  • @Paul9o7 创建足够大的数组(您必须在此处限制用户条目,如果同时接受 0 和 100,您可能不会超过 101 个条目)并计数条目。然后您可以遍历数组到条目数(因为 0 索引)并检查该数字是否已经存在。如果您已经在学校学习过搜索算法,您也可以使用它。
【解决方案2】:

使用std::find

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)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 2021-12-30
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多