Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I generate a four digits distinct random number with C++ using Visual Studios?
I used the following code but it only gives me random number of five digits(which is weird too because this code should generate some number really random.)

I need to generate a four digits random number and it must be distinct, than save it as an integer for comparison use later on.

C++
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(){
    srand(time(NULL)); //randomizes the seat
   cout << rand(); //prints a random positive integer;
}



The whole project is called Bulls and Cows. The player has seven (7) tries to guess the number. After every try, the player will be given feedback on their guess. Every correctly guessed number in the correct position counts as a bull (B). A correctly guessed number but in the wrong position counts as a cow (C). Two example runs of the program follow (user input is in italic).

Run 1:

Enter number: 2345
0B 1C
Enter number: 6789
0B 3C
Enter number: 3678
0B 2C
Enter number: 4967
0B 2C
Enter number: 5896
5896 is my number! You Win!

Run 2:

Enter number: 2345
0B 0C
Enter number: 6789
2B 0C
Enter number: 6701
2B 1C
Enter number: 8901
1B 2C
Enter number: 6910
0B 3C
Enter number: 1076
1B 2C
Enter number:  9710
1B 3C
Sorry you used all your guesses. You lose! My number was 1709.;
Posted
Updated 29-Oct-12 15:56pm
v2
Comments
nv3 30-Oct-12 8:49am    
What do you mean by the term "distinct"? Should all four decimal digits of the generated random number be different? Or should the generated 4-digit numbers be different from each other (in which case they would not be random numbers in the strict sense)?

1 solution

Look at http://msdn.microsoft.com/en-us/library/398ax69y.aspx[^]
The RangedRandDemo method shows how to generate random numbers over a specified range. You just want the range 0 .. 9999.
FYI: Using rand() % 10000 will give the numbers over that range, but they will not be uniformly distributed. For this "game" problem, that probably doesn't matter.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900