2014-01-09 38 views
-1

所以我正在研究這個基於數學控制檯的遊戲。參考我正在閱讀的這本書的章節。C++乘法遊戲分支語句問題

我希望能夠在使用no選項後退出遊戲。

問題是,當使用no選項時,程序將循環一次,然後退出。我希望程序立即退出。

我嘗試添加了其他選項,但它不斷給我的錯誤代碼:「(26):錯誤C2181:其他違法不若匹配」

而且任何人都可以告訴我,我怎麼能添加開關類爲遊戲添加更多菜單。這是否需要更多功能原型?

謝謝你所有的幫助堆棧溢出,我還在學習如何使用分支語句!

// 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; 

} 
+0

['rand()'認爲有害](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – TemplateRex

回答

2

看起來你缺少一些大括號。更改此塊...

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

...這個...

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

而且,它很可能是更好的改變本聲明

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

...這個...

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

這樣,只有'y'將被視爲確認。如果是其他方式,除'n'之外的任何內容都將被視爲確認。