2017-04-05 108 views
-3

我是新来的StackOverflow,也有些新的程序,所以请不要介意我的代码格式不佳。我的代码有两个问题。我的do ...逻辑和继续逻辑有什么问题?

  1. 我继续声明,如果玩家输入'y'或'Y',我用它来继续循环不起作用。它终止正确得到猜测后程序,这使我:

2.My继续计数器变为0过去不停止,我看不出我的错误在程序的逻辑。

我看不到我的逻辑问题。

#include "stdafx.h" 
    #include <iostream> 
    #include <iomanip> 
    #include <ctime> 
    #include <random> 

    using namespace std; 

    int getNumber(); //random number prototype 
    double getScore(); //gets score 
    int chances = 7; //chances to guess with 
    int main() 
    { 
    int guess = 0, 
     random; 
    char retry = 'y'; //initialize retry to 'y' 
    cout << "This is a random number guessing game. " << "You will be guessing between 1-100." 
    << "You have 7 chances. Good luck! \n \n" << endl; 


    random = getNumber(); //give the function a variable 

    do 
    { 

    cout << random << "\n" << "\n"; 
    chances--; 

    cout << "Enter your guess: "; 
    cin >> guess; 

     if (guess == random) 
     { 
      cout << "You have won the game! " << "Your score was: " << getScore(); 

      cout << "Would you like to retry? (Y or N): "; 
      cin >> retry; 

      if (retry == 'y' || retry == 'Y') 
      { 
       chances = 7; 
       guess = 0; 
       getNumber(); 
       continue; //player can retry the game 
      } 
      else if (chances == 0) 
      { 
       cout << "You have no chances left. Retry? (Y or N): "; 
        cin >> retry; 
       if (retry == 'y' || retry == 'Y') 
       { 
        chances = 7; 
        guess = 0; 
        getNumber(); 
        continue; 
       } 
      } 

       return 0; 
     } 
     else if (guess != random) 
      cout << "You got it wrong. \n" << "You have: " << chances << " chances left" << endl << endl; 
     else 
      cout << "Incorrect Input. Please type a number." << endl << endl; 
    } while (guess != random); 


return 0; 
} 

int getNumber() 
    { 
    unsigned seed = time(0); //seed the random number 
    srand(seed); 

    int randNum = rand() % 10 + 1; //random number in the range of 1-10 
    return randNum; 
    } 
+1

我不介意你可怜的格式。新的并不妨碍你花费一些时间和精力来很好地设计你的代码。举例来说,您可以查看任何现有的成功问题。 Stack Overflow有一个很棒的实时文章预览,所以你可以花费尽可能多的时间来创建好文章。 –

+1

'如果(重试==“Y” ||“Y”)'这并不做什么,你认为它 – JackVanier

回答

1

你会想看看this

continue语句跳跃至年底,并检查条件,guess != random,其计算结果为false,并退出do while。你需要做的是将猜测重置为一个值,例如0,以使条件确实计算为true

+0

谢谢你解释。我看不到发生了什么事。我不知道我必须重新设定猜测。我之所以必须重置它,是因为当它继续时,它会检查猜测是否等于随机,并且由于玩家正确,它会自动为假,退出游戏? –

2
if (retry == 'y' || 'Y') 

这是不正确的逻辑,这就是为什么你的代码不工作,你希望它的方式。你希望它是:

if (retry == 'y' || retry == 'Y') 

修复在其他if-else语句此逻辑错误也是如此。

+0

谢谢你,我甚至没有意识到这一点。我编辑了我的代码,但是当播放器输入时仍不会重启循环。我将继续寻找问题。再次感谢你! –

+0

@CoryAhapow如果我的答案有效,请选择我答案旁边的复选标记。当你这样做时它会变成绿色。谢谢! –