2013-11-01 3 views
-1

Полный код, который я использую, приведен ниже, он должен имитировать игру крэпов и распечатать информацию пользователю и разрешить делать ставки, если пользователь этого захочет. Все функционирует, за исключением реальной игры в крэпс. Вместо того, чтобы зацикливать только тогда, когда нет значения истинности, связанного с crapsResult, он находит одно реальное значение и непонятную строку из одного отрицательного числа. Любая помощь будет оценена по достоинству.Может ли кто-нибудь сказать мне, почему эти функции не дают мне результата в разумном спектре?

int main() 
{ 
    //Declare the user input variables 
    int gamesPlayed = 0; 
    char inputPrint = ' '; 
    char isBetting = ' '; 
    int startingBet = 0; 

    //Declare the variables used by the program 
    int endingBet = 0; 
    int currentGame = 0; 
    bool crapsResult; 
    int gamesWon = 0; 
    int gamesLost = 0; 
    double percentWon = 0; 
    bool detailPrint = false; 

    //Prompt the user to input their variables 
    cout << "Enter the number of games to be played: "; 
    cin >> gamesPlayed; 
    while(gamesPlayed < 1) 
    { 
     cout << " Error: must be greater than 0" << endl; 
     cout << "Enter the number of games to be played: "; 
     cin >> gamesPlayed; 
     cin.clear(); 
     cin.ignore(); 
    } 

    cout << "Do you wish to print details (Y/N): "; 
    cin >> inputPrint; 
    if(inputPrint == 'y' || inputPrint == 'Y') 
    { 
     detailPrint = true; 
    } 

    cout << "Do you wish to bet (Y/N): "; 
    cin >> isBetting; 

    if(isBetting == 'y' || isBetting == 'Y') 
    { 
     cout << "Enter money to start betting with: "; 
     cin >> startingBet; 
     while(startingBet < 1) 
     { 
      cout << " Error: must be greater than 0" << endl; 
      cout << "Enter the number of games to be played: "; 
      cin >> gamesPlayed; 
      cin.clear(); 
      cin.ignore(); 
     } 
    } 
    //Seed the random number generator 
    srand(time(NULL)); 

    //Set a value for ending bet 
    if(startingBet == 0) 
    { 
     endingBet = 1; 
    } 
    else 
    { 
     endingBet = startingBet; 
    } 
    //Call playcraps to simulate the game for as many games as the user input 
    for(currentGame = 1; currentGame <= gamesPlayed && endingBet > 0; currentGame += 1) 
    { 
     crapsResult = NULL; 
     crapsResult = playCraps(currentGame, detailPrint, isBetting, startingBet); 
     if(crapsResult == true) 
     { 
      gamesWon += 1; 
      endingBet = betting(endingBet, crapsResult); 
     } 
     if(crapsResult == false) 
     { 
      gamesLost += 1; 
      endingBet = betting(endingBet, crapsResult); 
     } 
     if((isBetting == 'Y' || isBetting == 'y') && (detailPrint == true)) 
     { 
      cout << "Money left is $" << endingBet << endl; 
     } 
    } 

    //Calculate the percentage of games won 
    percentWon = (double(gamesWon)/double(currentGame-1)) * 100.0; 

    //Print the results to the user 
    if(isBetting == 'Y' || isBetting == 'y') 
    { 
     cout << "Money at end of games is $" << endingBet << endl; 
    } 
    cout << "The number of games played is " << currentGame - 1 << endl; 
    cout << "The number of games won is " << gamesWon << endl; 
    cout << "The number of games lost is " << gamesLost << endl; 
    cout << "The percent of games won is " << fixed << showpoint << setprecision(3) << percentWon << endl; 
} 

//Simulates the roll of a single die and returns the result 
int roll() 
{ 
    int rollResult = 0; 
    rollResult = rand() % 6 + 1; 
    return rollResult; 
} 

//Calls roll twice and returns the sum of the two results 
int roll2Dice() 
{ 
    //Declare variables for this function 
    int rollOne = 0; 
    int rollTwo = 0; 
    int rollSum = 0; 

    //Find rollOne and rollTwo 
    rollOne = roll(); 
    rollTwo = roll(); 

    //Find rollSum 
    rollSum = rollOne + rollTwo; 

    return rollSum; 
} 

bool playCraps(int currentGame, bool detailPrint, char isBetting, int startingBet) 
{ 
    bool crapsResult = NULL; 
    int currentGameStorage[100]; 
    int currentRoll = 1; 
    int point = roll2Dice(); 
    int printingNumber = 0; 
    currentGameStorage[0] = point; 
    if(point == 7 || point == 11) 
    { 
     crapsResult = true; 
    } 
    else if(point == 2 || point == 3 || point == 12) 
    { 
     crapsResult = false; 
    } 
    else 
    { 
     crapsResult = NULL; 
    } 
    while(crapsResult != true && crapsResult != false) 
    { 
     currentGameStorage[currentRoll] = roll2Dice(); 
     if(currentGameStorage[currentRoll] == point) 
     { 
      crapsResult = true; 
     } 
     else if(currentGameStorage[currentRoll] == 7) 
     { 
      crapsResult = false; 
     } 
     currentRoll += 1; 
    } 
    if(detailPrint == true) 
    { 
     cout << "Game " << currentGame << ": "; 
     for(printingNumber = 0; printingNumber <= currentRoll; printingNumber += 1) 
     { 
      cout << currentGameStorage[printingNumber] << " "; 
     } 
     if(crapsResult == true) 
     { 
      cout << "win"; 
     } 
     else if(crapsResult == false) 
     { 
      cout << "lose"; 
     } 
     cout << endl; 
    } 
    return crapsResult; 
} 

int betting(int endingBet, bool crapsResult) 
{ 
    if(crapsResult == true) 
    { 
     endingBet += 1; 
    } 
    else if(crapsResult == false) 
    { 
     endingBet -= 1; 
    } 
    return endingBet; 
} 
+2

Пример вы вывесили очень долго, что делает его трудным для нас, чтобы изолировать точный вопрос. Не могли бы вы попытаться обрезать его до [короткого, самодостаточного, правильного, компилируемого примера] (http://sscce.org/)? Обязательно также проверьте [контрольный список вопросов] (http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist), чтобы убедиться, что у нас есть информация, необходимая для вас. Благодаря! –

ответ

3

Просто обезжиренное и не прочитал весь ваш код (так что могут быть и другие вещи тоже неправильно), но эта линия, безусловно, проблематично:

while(crapsResult != true && crapsResult != false) 

Это логически невозможно crapsResult к одновременно как true , так и false, так что цикл никогда не будет введен.

1

Turix получил право ошибку я верю, но я хотел бы сделать акцент на другом месте:

bool crapsResult = NULL; 

Вы пытаетесь использовать crapsResult для трех различных значений (true, false и NULL). Однако NULL обычно имеет целое значение 0, что соответствует логическому значению false, поэтому ваш цикл никогда не будет введен.

Тогда вторая ошибка входит в игру: currentRoll является 1 в это время, так что вы пытаетесь распечатать содержимое currentGameStorage из индекса от 0 до 1 (включительно), currentGameStorage[1] еще не назначена. Вот почему вы получаете критический номер в своем выходе. Это общая ошибка: ваш код всегда пытается напечатать один элемент слишком много. Используйте < вместо <= в голове петли, чтобы исправить это:

for(printingNumber = 0; printingNumber < currentRoll; printingNumber += 1) 
Смежные вопросы