Here is a simple C++ lottery program done for the KTSI.
#include <iostream> #include <cstdlib> using namespace std; int main (int argc, char * const argv[]) { int numberCount; int maxNumbers; cout << "Lottery Game" << endl << "=================================" << endl; cout << "How many Lottery Numbers = "; cin >> numberCount; cout << "from 1 to ? "; cin >> maxNumbers; cout << "You have chosen " << numberCount << " Lottery Numbers from 1 to " << maxNumbers << endl; int lotteryNumbers[numberCount]; int i, j; bool newNumber; srand(0); for(i=0; i<numberCount; i++) // get numbers { do { // Check Random lotteryNumbers[i] = rand() % maxNumbers + 1; newNumber = true; for (j=0; j<i; j++) { if (lotteryNumbers[j]==lotteryNumbers[i]) { // Check for existing numbers newNumber = false; } } } while (!newNumber); } for (i=0; i<numberCount; i++) { cout << lotteryNumbers[i] << " "; } cout << endl; }
Could you tell what I am doing wrong on this program. I am only getting two integers. I want the loop to perform five times and calculate r = rand_0toN1(56) + 1 and on the sixth time perform s = rand_0toN1(46) +1.
I am only getting to two integers.
// Test.cpp : main project file.
#include “stdafx.h”
#include “iostream”
#include “stdlib.h”
#include “time.h”
#include “math.h”
using namespace std;
//Declare functions before starting.
int rand_0toN1(int n);
void pick_a_number();
int main() {
int i;
int n;
srand(time(NULL)); //Set seed for random numbers.
cout << "Enter number of trials to run ";
cout <> n;
for( i = 1; i <= n; i++) {
pick_a_number();
}
return 0;
}
//Pick_a_number function
//Performs picking one num by getting a random 1-56 and
//a random 1-46. These are then used to index the string arrays,
// rows.
void pick_a_number() {
int i;
int r; //Random index (1 thru 56)
int s; //Random index (1 thru 46)
i = 0;
while (i < 6) {
if (i != 6)
r = rand_0toN1(56) + 1;
else if (i == 6)
s = rand_0toN1(46) + 1;
i++;
}
cout << r << " " << s << " "; //Print out results.
}
//Random 1-to-N function.
//Generate a random integer from 1 to N, giving each
//integer an equal probability.
int rand_0toN1(int n) {
return (rand() % n) + 1;
}