如何使用C ++生成4个数字不同的随机数? [英] How can I generate 4 ditgits distinct Random Number with C++?

查看:308
本文介绍了如何使用C ++生成4个数字不同的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Visual Studio使用C ++生成四位数的不同随机数?
我使用了以下代码,但它只给我五位数的随机数(这也很奇怪,因为此代码应该生成一些真正随机的数字.)

我需要生成一个四位数的随机数,并且必须与众不同,而不是将其另存为整数以便以后进行比较.

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.

#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;
}




整个项目称为Bulls and Cows.玩家有七(7)次尝试猜数字.每次尝试后,都会向玩家提供有关其猜测的反馈.在正确位置的每个正确猜中的数字都算作公牛(B).正确猜中但位置错误的数字将算作母牛(C).下面是该程序的两个示例运行(用户输入以斜体显示).




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.;

推荐答案

查看
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.


这篇关于如何使用C ++生成4个数字不同的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆