2016-11-04 7 views
-4

Мне нужна помощь с моей программой, когда пользователь вводит номер, который не является победителем в лотерее, он все еще говорит победителю любое предложение, как исправить это, если бы вы могли дать мне лучше предложения по моей линейной функции поиска, было бы удивительно, вот мой код:моя программа не использует определенную часть моего кода

#include <iostream> 
#include <cstdlib> 
using namespace std; 

bool input(double); 

const int LUCKY_NUMS =10; 

// Function prototype that searches winning ticket number 
bool ticketSearch(const int [], int, int); 

int main() 
{ 
    //user continues playing lotto 

    char again; 

    const char QUIT = 'N'; 
    //determines if player's ticket is a winner 

    int winningNum; 
    //5 digit ticket number entered by player 

    int playerNum; 
    //holds winning ticket number 

    int ticket; 

    //Array holding the winning tickets for each week 

    int lottoTix[LUCKY_NUMS] = {13579, 26791, 26792, 33445, 55555, 
           62483, 77777, 79422, 85647, 93121}; 

    //Player decides if they want to continue playing 

      for (int week = 0; week < 10; week++) 
      { 
      //Winning lotto ticket for each week (10 weeks total) 

       ticket = lottoTix[week]; 
       do 
       { 
        cout << "Please enter your 5-digit ticket number for  week " << (week + 1) << ": " << endl; 

      //Player's ticket number 

      cin >> playerNum; 
      }while(input(playerNum)); 



      //Calls linear search for winning lotto ticket 

      winningNum = ticketSearch(lottoTix, LUCKY_NUMS, playerNum); 

      //Error message if player's number is not the winning ticket 
      //here is where my problems occurs it doesn't use this part of code at all 
      if (playerNum != lottoTix[LUCKY_NUMS]) 
      { 

       cout << "Sorry, you did not win the MEGAMILLIONS lottery. "; 
       cout << "Thanks for playing! "; 
       cout << "Play again? (Y/N)"; 
        cin >> again; 
      } 

      //Player wins the lottery 
      else if (playerNum == lottoTix[LUCKY_NUMS]) 
      { 

       cout << "You have just won 598 MILLION DOLLARS!!! "; 
       cout << "CONGRATULATIONS!!!"; 
       cout << "Play again? (Y/N)"; 
       cin >> again; 
      } 


      if ((again != 'Y') && (again != 'y')) 
       { 
        //exit message 
        cout << "Press [Enter] to exit...\n\n"; 
        //exits program 
        exit(0); 
       } 
     } 
    return 0; 
} 

//linear search for winning ticket of the week 
bool ticketSearch(const int ticketList[], int numTickets, int winningNum) 
{ 
int index = 0; 
int position = -1; 
bool found = false; 

while ((index < numTickets) && !found) 
{ 
    if (ticketList[index] == winningNum) 
    { 
     found = true; 
     position = index; 
    } 
    index ++; 
    } 
    return found; 
} 
// function does invalid input 
bool input(double number) 
{ 
if (number < 0 || number >=99999 || cin.fail()) 
{ 
    cin.clear(); 
    cin.ignore(); 
    cout <<"\nYou have entered an invalid answer\n" << endl; 
    return true; 
} 
else 
    return false; 

}

Я знаю, что есть, вероятно, некоторые ошибки пунктуации, но это, вероятно, самый простой thingt исправить

+0

Пожалуйста, отредактируйте ваш вопрос, чтобы предоставить [mcve]. –

+0

Правильный инструмент для решения таких проблем - ваш отладчик. Перед тем, как просить о переполнении стека, вы должны пропустить свой код по очереди *. Для получения дополнительной информации, пожалуйста, прочтите [Как отлаживать небольшие программы (Эрик Липперт)] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Как минимум, вы должны \ [изменить] ваш вопрос, чтобы включить пример [Минимальный, полный и проверенный] (http://stackoverflow.com/help/mcve), который воспроизводит вашу проблему, а также замечания, сделанные вами в отладчик. –

+0

Почему вы сравнили playerNum с lottoTix [LUCKY_NUMS]? (LUCKY_NUMS является константным целым числом) –

ответ

1

проблема с вашим кодом заключается в том, что значение, которое вы получаете от functi on должно быть логическим. victoryNum - целое число. Кроме того, вы можете использовать что-то вроде «если элемент найден», а затем что-то делать. Вы также можете использовать цикл for для линейного поиска.