【问题标题】:c++ multiplication game branching statement issuec++乘法游戏分支语句问题
【发布时间】:2014-01-09 19:33:13
【问题描述】:

所以我正在开发这款基于数学控制台的游戏。完成我正在阅读的这本书的章节。

我希望能够在使用 no 选项后退出游戏。

问题是当使用 no 选项时,程序会循环一次然后退出。我希望程序立即退出。

我尝试添加一个 else 选项,但它一直给我错误代码:“(26):错误 C2181:非法 else 不匹配 if”

还有谁能告诉我如何添加开关类来为游戏添加更多菜单。这需要更多的函数原型吗?

感谢您对堆栈溢出的所有帮助,我仍在学习如何使用分支语句!

    // multiplicationgame.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

void game();

int _tmain(int argc, _TCHAR* argv[])
{
    char choice = 0;
    game();
    while(choice != 'n')
    {

    cin >> choice;

    if (choice == 'y')
    cout << "\n\n";
    game();

    //else
    //cout << "later";
    //
    }


    return 0;
}

void game()
{
    srand(time(NULL));
    int a = rand() % 23;
    int b = rand() % 23;
    int c = (a * b);
    int d = 0;
    char choice = 0;

    cout <<"What does " << a << " * " << b << " equal?" << endl << endl << endl;
    cout << "\n";

    while(d != c)
    {
        if(d != c)
        {
        cout << "Please enter a number: ";
        cin >> d;
        }
    }
    cout << "\n\nCorrect! " << (a * b) << " is the answer!" << endl << endl;

    cout << "Play again (Y) or (N)?" << endl;

}

【问题讨论】:

标签: c++ function if-statement multiplication


【解决方案1】:

看起来您缺少一些大括号。更改此块...

if (choice == 'y')
cout << "\n\n";
game();

……到这个……

if (choice == 'y')
{
    cout << "\n\n";
    game();
}

另外,更改此语句可能会更好......

while(choice != 'n')
{
    …
}

……到这个……

while(choice == 'y')
{
    …
}

这样,只有'y' 会被视为确认。如果是另一种方式,'n' 以外的任何内容都将被视为确认。

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 2020-06-16
    • 2014-01-30
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    相关资源
    最近更新 更多