0

我不明白它到底有什么问题。最后的尝试次数是 9,即使有一个 while 循环。我希望它检查猜测是字符串中的坐标之一,但它永远不会起作用。:/

我会在哪里移动 if 语句?

int main() {
int guesses, destroy, numAttempts = 11;
string guess, i;
string coordinate[3] = {"B1", "C4", "D3"};

cout << "Enter in a coordinate between A-1 and D-4 (i.e. C4): ";
cin >> guess;

guesses = 0;
destroy = 0;
while (guess != coodinate[i] && guesses < numAttempts - 1) {
    cout << "Target missed. Try again: ";
     cin >> guess;
     guesses++;;
}
if (guess != coordinate[i])
    cout << "Failed!";
else
    cout << "Congrats!";

  /*if (guess == coordinate) {
     cout << "Target hit! Next target: ";
     cin >> guess;
 destroy++;
 guesses++;

 }
 */

}
4

3 回答 3

2

你忘了增加i.. i++(至少,我假设你是?)。可能是错误的一部分。如果您必须增加 i,请确保它不会超出范围。

   guess = input ;
   guesses = 0;
   while (guesses < numAttempts  && guess != coodinate[i] ) { 
     cout << "Target missed. Try again: ";
     cin >> guess;
     guesses++;
     i = (i+1)%3;
   }
于 2013-04-28T16:34:43.397 回答
1

你这里有一个错字:

while (guess != coodinate[i] && guesses < numAttempts - 1) 
              //coordinate[i]

尝试 :

while ((guess != coordinate[i]) && (guesses < (numAttempts - 1))) 
//Parenthesis are not mandatory

另外,正如其他人指出的那样,您不是在寻找guess所有 array中的值coordinate,因为您没有 increment i

于 2013-04-28T16:33:18.010 回答
0

您将需要学习创建小型的单一用途功能并将它们组合在一起。

#include <set> // because you have a set of targets...
#include <string> // used to represent a target

using Target = std::string;

static Target const MissedTarget = "";

static bool isGuessCorrect(Target const& guess,
                           std::set<Target> const& targets)
{
    return targets.count(guess);
}

// Returns the target hit (if any), or MissedTarget otherwise
static Target tryOnce(std::set<Target> const& targets) {
    std::cout << "Enter in a coordinate between A-1 and D-4 (i.e. C4): ";

    std::string guess;
    if (std::cin >> guess) {
        if (isGuessCorrect(guess, targets)) { return guess; }

        return MissedTarget;
    }

    // Something that could not (unfortunately) be parsed,
    // we need to clear std::cin
    std::cin.clear();
    std::cin.ignore(std::numeric_limit<size_t>::max(), '\n');

    return MissedTarget;
}

static bool tryFewTimes(size_t const tries, std::set<Target>& targets) {
    for (size_t n = 0; n != tries; ++n) {
        Target const target = tryOnce(targets);

        if (target == MissedTarget) {
            std::cout << "Missed! Try again!\n";
            continue;
        }

        targets.erase(target);

        std::cout << "Congratz! You got " << target
                  << "! Only " << targets.size() << " remaining\n";
        return true;
    }

    std::cout << "You flunked it, can't always win :(\n";
    return false;
}


int main() {
    std::set<Target> targets = { "A1", "B1", "C1" };

    while (not targets.empty() and tryFewTimes(3, targets)) {}
}
于 2013-04-28T17:22:50.010 回答