简体   繁体   English

尝试一次取一个随机数

[英]Trying to take 1 random digit at a time

I am new to cpp programing, and new to stackoverflow. 我是cpp编程的新手,也是stackoverflow的新手。

I have a simple situation and a problem that is taking more time than reasonable to solve, so I thought I'd ask it here. 我有一个简单的情况,一个问题花了比合理的时间更多的时间来解决,所以我想在这里问。

I want to take one digit from a rand() at a time. 我想一次从rand()中取一位数。 I have managed to strip of the digit, but I can't convert it to an int which I need because it's used as an array index. 我设法去除了数字,但由于将其用作数组索引,因此无法将其转换为所需的int

Can anyone help? 有人可以帮忙吗? I'd be appreciative. 我会很感激的。

Also if anyone has a good solution to get evenly-distributed-in-base-10 random numbers, I'd like that too... of course with a rand max that isn't all 9s we don't have that. 另外,如果有人有很好的解决方案来获得以10为基数均匀分布的随机数,我也想这样做……当然,由于rand max并非全为9,我们就没有这个。

KTM 韩国电信

Well you can use the modulus operator to get the digit of what number rand returns. 好了,您可以使用模运算符获得兰德返回的数字。

int digit = rand()%10;

As for your first question, if you have a character digit you can subtract the value of '0' to get the digit. 关于第一个问题,如果您有字符数字,则可以减去'0'的值以获得数字。

int digit = char_digit - '0';

If one wants a pedantic even distribution of 0 to 9 one could 如果想要一个0到9的均匀分布,可以

  1. Assume rand() itself is evenly distributed. 假设rand()本身是均匀分布的。 (Not always a good assumption.) (并不总是一个很好的假设。)

  2. Call rand() again as needed. 根据需要再次调用rand()

     int ran10(void) { const static int r10max = RAND_MAX - (RAND_MAX % 10); int r; while ((r = rand()) >= r10max); return r%10; } 

Example: 例:
If RAMD_MAX was 32767, r10max would have the value of 32760. Any rand value in the range 32760 to 32767 would get tossed and a new random value would be fetched. 如果RAMD_MAX为32767,则r10max的值为r10max将扔掉32760到32767范围内的所有rand值,并获取一个新的随机值。

While not as fast as modulo-arithmetic implementations like rand() % 10 , this will return evenly distributed integers and avoid perodicity in the least significant bits that occur in some pseudo-random number generators (see http://www.gnu.org/software/gsl/manual/html_node/Other-random-number-generators.html ). 尽管不如rand() % 10这样的模数算法实现快,但它会返回均匀分布的整数,并避免某些伪随机数生成器中发生的最低有效位出现周期性(请参阅http://www.gnu.org)。 /software/gsl/manual/html_node/Other-random-number-generators.html )。

int rand_integer(int exclusive_upperbound)
{
        return int((double)exclusive_upperbound*rand()/RAND_MAX);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM