奶牛和公牛队比赛 - C ++

时间:2014-06-13 13:20:41

标签: c++

问题 - 实施一款名为Cows and Bulls的猜谜游戏。奶牛代表正确猜测的数量。公牛代表正确位置的正确猜测量。例如,计算机具有1234并且用户猜测2135结果是:1头公牛和3头奶牛。

我已经写了代码,但我一直得到0公牛和0牛。我玩了一个多小时,似乎仍然无法找到问题。这个版本是用字符而不是数字完成的,但适用相同的规则。

#include "std_lib.h";

vector<char> letters;
vector<char> answers;

void defineletters() {

  letters.push_back('a');
  letters.push_back('b');
  letters.push_back('c');
  letters.push_back('d');
}

int testcows(char a) {

  int manycows = 0;

  for (int i = 0; i < letters.size(); ++i) {
    if (a == letters[i]) {
      ++manycows;
    }
  }

  return manycows;
}

int testposition() {

  int manybulls = 0;

  for (int i = 0; i < letters.size(); ++i) {
    if (answers[i] == letters[i]) {
      ++manybulls;
    }
  }

  return manybulls;
}

int main() {

  int cows = 0;

  char answer1;
  char answer2;
  char answer3;
  char answer4;

  cin >> answer1 >> answer2 >> answer3 >> answer4;
  answers.push_back(answer1);
  answers.push_back(answer2);
  answers.push_back(answer3);
  answers.push_back(answer4);

  cows = testcows(answer1) + testcows(answer2) + testcows(answer3) +
         testcows(answer4);

  cout << testposition() << "Bulls\n" << cows - testposition()
       << "Cows\n";

  keep_window_open("-");
}

2 个答案:

答案 0 :(得分:1)

永远不会调用defineletters(),因此向量永远不会被初始化,因此长度为零。

答案 1 :(得分:1)

永远不会调用

defineletters - &gt;字母未初始化