Функция, которая конвертирует количество совпадений в выигрышный приз - PullRequest
0 голосов
/ 24 февраля 2019

Я создаю программу лотереи, которая генерирует тикет из 5 случайных чисел в диапазоне от 1 до 36.Пользователь может выбрать, сколько билетов он хочет, что является моим для цикла в основном.Я выполнил большую часть кода, но у меня возникли проблемы с созданием функции, которая преобразует количество найденных совпадений в призовой выигрыш в массиве, который объединит выигрыши после окончания цикла for.Все работает нормально, но у меня возникают проблемы с пониманием того, как я могу сохранить выигрыши из цикла for в другой массив, чтобы я мог объединить общее количество выигрышей.Вот мой код.

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <stdio.h>
#include <algorithm>

using namespace std;

const int ARRAY_SIZE = 5; //size of the array

//function prototypes
void generateWinning (int [], int);
void genTicket(int[], int);
void bubbleSort(int [], int);
void findMatch(int [], int [], int[]);
void printArray(int [], int);
void printWinning(int);

int main()
{
srand( time(NULL) );

int numTickets, j;

int totalWinnings[4]={0,0,0,0};
int lottery[ARRAY_SIZE]; //holds winning lottery
int user[ARRAY_SIZE]; //holds users number of ticks

cout << "Enter number of tickets: ";
cin >> numTickets;
   generateWinning (lottery, ARRAY_SIZE); //generate winning tickets, then 
//display
   printArray(lottery, ARRAY_SIZE);
   for( int i=0; i < numTickets; i++)//loop amount of times user chooses tickets
        {
        genTicket(user, ARRAY_SIZE);//generate random numbers without duplicates
        bubbleSort(user, ARRAY_SIZE);//sort list of array sorted.
        printArray(user, ARRAY_SIZE); //print results.
        findMatch(lottery,user, totalWinnings);//find matches then store 
//them into totalWinning Array

        }
printArray(totalWinnings, 4);
   //j=0;
   //int total = totalWinnings[j] + totalWinnings[j+1] + totalWinnings[j+2] 
+ totalWinnings[j+3];

  //cout << "You Total Prize Amount = "<< "$" << total <<endl;

        return 0;
}
void printArray(int arr[], int size)
{
        int i;
        for (i=0; i < size; i++)
        {
           printf("%d", arr[i]);
           printf(" ");
        }
        cout << endl;
}
void generateWinning(int lottery[], int ARRAY_SIZE)
{
        cout << "Winner ";
        int index =0;
        int lotteryPool[36];
        for(int x = 0; x<36; x=x+1)
        {
        lotteryPool[x]=x+1;
        }
        random_shuffle(&lotteryPool[0], &lotteryPool[35]);
        while (index < ARRAY_SIZE)
        {
          lottery[index] = lotteryPool[index];
          index++;
        }
        bubbleSort(lottery,ARRAY_SIZE);
}
void genTicket(int arr[], int ARRAY_SIZE)
{
        int index=0;
        int lotteryPool[36];
        for (int x=0; x<36; x=x+1)
        {
        lotteryPool[x]= x+1;
        }
        random_shuffle(&lotteryPool[0], &lotteryPool[35]);
        while (index < ARRAY_SIZE)
        {
        arr[index] = lotteryPool[index];
        index++;
        }
}

void bubbleSort(int user[], int ARRAY_SIZE)
{
        int i, j, temp;
        for (i=1; i < ARRAY_SIZE; ++i)
        {
           for(j=0; j<(ARRAY_SIZE-i); ++j)
           {
              if (user[j] > user[j+1])
              {
              temp = user[j];
              user[j]=user[j+1];
              user[j+1] = temp;
              }
           }
        }
}
void findMatch(int user[], int lottery[], int winning[])
{
        int index, temp;
        int matches = 0;
        for(int index = 0; index < ARRAY_SIZE; index++)
        {
           for(int temp =0; temp < ARRAY_SIZE; temp++)
           {
                  if(lottery[index]==user[temp])
                  {
                matches++;
              }
              else
              {
              cout <<"";
              }
           }
        }
        cout << matches << endl;
        int i;
           if (matches == 2)
           {
           winning[i]=1;
           }
           else if (matches == 3)
           {
           winning[i]=10;
           }
           else if(matches == 4)
           {
     winning[i]=500;
           }
           else if (matches = 5)
           {
           winning[i]=25000;
           }


}


This is my output:
Enter number of tickets: 5
Winner 2 9 14 30 33
7 11 14 16 29
1
10 14 33 34 35
2
1 8 12 25 34
1
6 13 25 28 33
1
2 3 11 13 26
1
0 0 0 0 //why is this not storing match that equal prize?

1 Ответ

0 голосов
/ 24 февраля 2019

Ваша проблема в том, что вы вызываете неопределенное поведение в этой части вашего кода:

       // in findMatch
       int i; // i is uninitialized
       if (matches == 2)
       {
           winning[i]=1; // using i as an array index results in undefined behavior
       }
       else if (matches == 3)
       {
           winning[i]=10;
       }
       else if(matches == 4)
       {
          winning[i]=500;
       }
       //else if (matches = 5) // typo in the operator here 
       else if (matches == 5)
       {
          winning[i]=25000;
       }

Чтобы исправить это, просто добавьте i в качестве параметра к вашей функции и избавьтесь от int i; в findMatch:

void findMatch(int user[], int lottery[], int winning[], int i)
{ ... }
...