-
February 24th, 2013, 01:26 PM
#1
Unique random numbers in an array
Below is my code for a program that is suppose to generate and display six unique random numbers (between 1 and 54). The issue seems to be in my check for duplicates. I know what I am doing wrong but can't seem to find a way to fix it. I think it is getting stuck in an endless loop because the way I have written it looks like it checks the first value against itself which will of course look like a duplicate everytime. I am relatively new to programming, but catch on quickly....just a point in the right direction would be of immense help. Thanks.
Code:
#include<iostream>
#include<ctime>
using namespace std;
//function prototype
int getRandNumb();
int main ()
{
srand((unsigned)time(NULL));
//declare array
int randomNum[6];
//declare variable
int checkNum = 0;
for (int x = 0; x < 6; x += 1)
{
randomNum[x] = getRandNumb();
if (randomNum[x] == randomNum[0] || randomNum[1] || randomNum[2] || randomNum[3] ||randomNum[4] || randomNum[5])
x -= 1;
else
cout << randomNum[x] << endl;
} //end for
cin.get();
return 0;
} //end of main function
//*****function definition(s)*****
int getRandNumb()
{
return rand()%54 - 1 + 1;
} //end of getRandNumb function
-
February 24th, 2013, 01:38 PM
#2
Re: Unique random numbers in an array
Code:
if (randomNum[x] == randomNum[0] || randomNum[1] || randomNum[2] || randomNum[3] ||randomNum[4] || randomNum[5])
That's not how you write multiple conditions in C++. randomNum[1] is an expression by itself, so unless it's 0, the entire statement will always be true. The way you wrote the first check is the way you need to write them all.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|