【发布时间】:2017-04-05 21:50:03
【问题描述】:
我是 stackoverflow 的新手,对编程也有些陌生,所以请不要介意我的代码格式不佳。我的代码有两个问题。
- 如果玩家键入“y”或“Y”,我用来继续循环的 continue 语句不起作用。它在只有正确猜测后终止程序,这导致我:
2.我的 continue 计数器在没有停止的情况下超过 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;
}
【问题讨论】:
-
我确实介意你糟糕的格式。成为新人并不妨碍您花费一些时间和精力来很好地格式化您的代码。您可以查看任意数量的现有成功问题作为示例。 Stack Overflow 具有出色的实时帖子预览功能,因此您可以根据需要花费尽可能多的时间来使帖子看起来不错。
-
if(retry=='y' || 'Y')这并不像你认为的那样