-2

我的游戏有效,但不是“错误的猜测”部分,“错误”的意思是“即使我的猜测是正确的,它也说我错了,或者它说错了好几次,而不仅仅是一次”。

所以,在我的初学者程序中,这就是我卡住的地方。

char u_recherche;  
std::string mot_secret(choisi_ton_mot.length(), '-');  
std::string choisi_ton_mot;  
int faute = 0;

 while (i < 999)                                       
    {
        //code

        for (int i = 0; i < mot_secret.length(); i++) // to check each letter
        {
            if (choisi_ton_mot[i] == u_recherche) //guess right
            {
                mot_secret[i] = u_recherche; // if right change "-" to the right letter
                std::cout << "lettre trouver ! " << std::endl;
            }
        }
        if (choisi_ton_mot[i] != u_recherche) //guess wrong
        {
            std::cout << "rater !" << std::endl;
            faute++;
        }

`

4

1 回答 1

0

除了您的代码不完整之外,实际错误很容易发现:

  1. 你有两个循环。外部“while”循环和内部“for”循环。它们都使用“i”作为索引,所以内部的“i”隐藏了外部。这本身不是错误,但很容易导致其他错误,例如在您的程序中。

  2. 您的第二个“if”,即检查错误猜测的那个,位于“for”循环之外,这意味着使用的“i”是外部的,而不是您想要使用的。

  3. 只有当正确的猜测没有出现时,才应该触发错误的猜测代码。一种方法是引入一个辅助变量

因此,考虑到这一点,它可以重写为:

int tries = 0;
while (tries < 999)                                       
    {
        //code
        
        bool guess_wrong = true;
        for (int i = 0; i < mot_secret.length(); i++) // to check each letter
        {
            if (choisi_ton_mot[i] == u_recherche) //guess right
            {
                guess_wrong = false
                mot_secret[i] = u_recherche; // if right change "-" to the right letter
                std::cout << "lettre trouver ! " << std::endl;
            }
        }
        if (guess_wrong)
        {
            std::cout << "rater !" << std::endl;
            faute++;
        }
...
于 2021-01-27T19:14:47.410 回答