本文介绍了使用Rand()在C ++中获取一个8位数的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以向我解释为什么这不起作用,它的编译但不给我结果..阅读除了couts之外的评论,看看它的作用。我真的尝试了一切,没有任何运气。
Could someone please explain to me why this is not working, its compiling but not giving me the results.. read the comments besides the couts to see what its doing. I have literally tried everything and not having any luck whatsoever.
int i;
srand (time(NULL));
i = (rand() % 99999999 + 1);
cout << i << endl; //This cout displays a 5 digit number that counts upwards every time
i = 0;
while (i < 99999999)
{
i = (rand() % 99999999 + 1);
}
cout << i << endl; //This one stalls my program
推荐答案
long FourDigitRandom()
{
return (long) rand() % (9999 + 1);
}
...
long l = FourDigitRandom() + (FourDigitRandom() * 10000);
...
int value = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)
+ range_min;
,如下例 []
在您的情况下,range_max = 99999999和range_min = 1.
或者,如果你想确保它总是8位数而没有前导零,那么range_min = 10000000.
问候,
Ian。
as given in the example here rand()[^]
In your case, range_max = 99999999 and range_min = 1.
Or, if you want to ensure it is always 8 digits without leading zeros, then range_min = 10000000.
Regards,
Ian.
int i = 0,j = 0;
i = rand() % 9 + 1; //First number should not be 0.
for (int k = 1; k < 4; k++) {
i = i*10 + rand()%10; //Generate the next 3 digits.
}
for (int k = 0; k < 4; k++) {
j = j*10 + rand()%10; //Generate the 4 digits of the lower part.
}
cout<<"Random number : "<<i<<j;
// If you want the 8 digit number, save in long int
long int res = i*1000 + j;
cout<<res;
这篇关于使用Rand()在C ++中获取一个8位数的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!