다른 사람들이 프로그램의 논리에 도움이 될 것이라고 판단하므로 구조를 도와 드리겠습니다. 즉, 어떻게 프로그램을 논리적으로 설명했는지 그리고 어떻게하면 더 잘할 수 있을지 생각해보십시오. 실제로 여기서 코드를 실행하지는 않았습니다. 지금은 그렇게 할 수있는 환경이 없습니다.
코드를 자동 포맷하고 do-while 루프에서 간단한 while 루프로 마이그레이션하는 것으로 시작했습니다. 또한 변수 선언을 사용하는 곳으로 옮겼습니다. 실제 세계에서 일부 코딩 표준은 마지막 단계를 금지하지만, 프로그램의 가독성을 향상시키고 내 논리를 이해하는 데 도움이된다고 생각합니다.
enum statuses { NEUTRAL, HIGH, LOW };
int status = NEUTRAL;
char input;
int cpuguess, high = 100, low = 1;
bool playing = true; // use booleans to represent true/false state, rather than characters
while (playing) { // "playing" closer to declaration = arguably easier to read & find purpose
cout << "Guess My Number" << endl << endl;
cout << "Press Enter to Play !" << endl;
cin.ignore();
cin.get();
bool gameWon = false;
while (!gameWon) {
cpuguess = getGuess(status, high, low);
cout << "Is your guess " << cpuguess << " ?" << endl;
cout << "(y/n)";
cin >> input;
gameWon = toupper(input) == 'Y';
if (!gameWon)
{
status = NEUTRAL;
while (status == NEUTRAL) {
cout << "Too HIGH or Too LOW ? O_O" << endl;
cout << "(h/l)";
cin >> input;
input = toupper(input);
if (input == 'H') {
status = HIGH;
high = cpuguess;
} else if (input == 'L') {
status = LOW;
low = cpuguess;
}
}
}
}
cout << "I won ! :D" << endl << endl;
cout << "Do you want to play again ?" << endl;
cout << "(y/n)" << endl;
cin >> input;
playing = toupper(input) == 'Y';
}
- 프로그램에서
, 당신은 종종 사용자가 두 개의 답 중 하나를주고 싶다. 사실
과 비슷한 코드가 표시됩니다.
cout << "Is your guess " << cpuguess << " ?" << endl;
cout << "(y/n)";
cin >> input;
gameWon = toupper(input) == 'Y';
3 번! 아마도 getAnswer라는 새로운 함수를 도입하여 질문과 두 가지 가능한 답변 (예 : 'y'및 'n')을 얻고 사용자의 대답을 반환 할 수 있습니다. 또한 대문자 Y/N 옵션을 일관되게 인쇄하도록 선택했으며 '\ 0'을 사용자가 입력하지 않을 값으로 간주했습니다. 따라서 option1 또는 option2가 소문자이면 프로그램이 더 이상 제대로 작동하지 않습니다. getAnswer 함수의 시작 부분에 option1과 option2 isupper (c)를 확인하는 것과 같은 여러 가지 방법으로 처리 할 수 있습니다. 여기서는 그렇게하지 않았습니다.
char getAnswer(const char * question, const char option1, const char option2);
void main() { // or whatever entry-point signature you've used
enum statuses { NEUTRAL, HIGH, LOW };
int status = NEUTRAL;
char input;
int cpuguess, high = 100, low = 1;
bool playing = true; // use booleans to represent true/false state, rather than characters
while (playing) { // "playing" closer to declaration = arguably easier to read & find purpose
cout << "Guess My Number" << endl << endl;
cout << "Press Enter to Play !" << endl;
cin.ignore();
cin.get();
bool gameWon = false;
while (!gameWon) {
cpuguess = getGuess(status, high, low);
stringstream ss;
ss << "Is your guess " << cpuguess << " ?";
gameWon = getAnswer(ss.c_str(), 'Y', 'N') == 'Y';
if (!gameWon) {
status = getAnswer("Too HIGH or Too LOW ? O_O", 'H', 'L') == 'H' ? HIGH : LOW;
if (status == HIGH)
high = cpuguess;
else
low = cpuguess;
}
}
cout << "I won ! :D" << endl << endl;
playing = getAnswer("Do you want to play again?", 'Y', 'N') == 'Y';
}
}
char getAnswer(const char * question, const char option1, const char option2) {
char response = '\0';
while (response != option1 && response != option2) {
cout << question << endl;
cout << "(" << option1 << "/" << option2 << ")" << endl;
cin >> response;
response = toupper(response);
}
return response;
}
신난다, 우리의 코드는 단지에서 많은 청소기를 보이지만, 우리는 여전히 논리적 조각으로 우리의 코드를 파손, 그래서 그 일을 시도 할 수 없다. 내가 당신의 콘솔 아웃풋을 외부 while 루프 밖으로 옮기고 '당신의 숫자'라고 '당신의 추측이다'라고 바꿨습니다. 이전에, 사용자가 다시 놀고 싶다고 말하면, 짜증나는 그 후에 enter를 눌러야했습니다!
enum class GuessStatus { NEUTRAL, HIGH, LOW }; // I elected to use c++11's 'enum class'
// these are called forward declarations
void runIntroduction();
void playGame();
// I elected to use const char * and const char here. They weren't necessary, though.
char getAnswer(const char * question, const char option1, const char option2);
void main() { // or whatever entry-point signature you've used
runIntroduction();
bool playing = true; // use booleans to represent true/false state, rather than characters
while (playing) { // "playing" closer to declaration = arguably easier to read & find purpose
playGame();
playing = getAnswer("Do you want to play again?", 'Y', 'N') == 'Y';
}
}
void runIntroduction() {
cout << "Guess My Number" << endl << endl;
cout << "Press Enter to Play !" << endl;
cin.ignore();
cin.get();
}
void playGame() {
int guessHigh = 100, guessLow = 1;
GuessStatus status = GuessStatus::NEUTRAL; // I'd suggest having GuessState::INITIAL = NEUTRAL to improve readability. Either that, or throwing in a comment to describe why you use NEUTRAL.
bool gameWon = false;
while (!gameWon) {
int cpuguess = getGuess(status, high, low);
stringstream ss;
ss << "Is your number " << cpuguess << " ?";
gameWon = getAnswer(ss.c_str(), 'Y', 'N') == 'Y';
if (!gameWon) {
status = getAnswer("Too HIGH or Too LOW ? O_O", 'H', 'L') == 'H' ? GameStatus::HIGH : GameStatus::LOW;
if (status == GameStatus::HIGH)
high = cpuguess;
else // status == GameStatus::LOW
low = cpuguess;
}
}
cout << "I won ! :D" << endl << endl;
}
char getAnswer(const char * question, const char option1, const char option2) {
char response = '\0';
while (response != option1 && response != option2) {
cout << question << endl;
cout << "(" << option1 << "/" << option2 << ")" << endl;
cin >> response;
response = toupper(response);
}
return response;
}
그게 전부입니다. 혼란스러운 점이 있다면 질문하십시오.
우리는 추측 할 필요가 없도록'getGuess' 함수를 포함해야합니다. – Matt
Re : '개선 할 수있는 다른 조언은 너무 환영합니다.': 더 많은 전문 지식을 얻을 때까지 goto를 사용하지 말라는 조언을드립니다. (그들은 일반적으로 눈살을 찌푸리고 많은 사람들이 전혀 사용하지 마십시오.) 그들은 종종 프로그램을 제대로 구성하지 않았고 논리가보다 명확하고 명확한 방법으로 윤곽을 잡을 수 있다는 지표를 사용합니다. – Warty
omg gotos .... burn it –