0

何が悪いのか正確にはわかりません。while ループがあっても、最終的な試行回数は 9 回です。推測のチェックが文字列の座標の1つであることを確認したいのですが、うまくいきません。:/

そして、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すべての配列coordinateで値を探しているわけではありません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 に答える