尝试一次取1个随机数字 [英] Trying to take 1 random digit at a time

查看:128
本文介绍了尝试一次取1个随机数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是cpp编程的新手,是stackoverflow的新手。

I am new to cpp programing, and new to 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.

我想从 rand()中取一个数字。我已经设法删除了数字,但我不能将其转换为 int ,因为它用作数组索引,我需要。

I want to take one digit from a rand() at a time. 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.

任何人都可以帮助?

此外,如果任何人有一个好的解决方案,以获得均匀分布在基地10随机数,我也喜欢。 。

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.

KTM

推荐答案

如果想要一个0到9的平均分布,可以

If one wants a pedantic even distribution of 0 to 9 one could


  1. rand()本身是均匀分布的。 (不总是一个好的假设。)

  1. Assume rand() itself is evenly distributed. (Not always a good assumption.)

根据需要再次调用 rand() >

Call rand() again as needed.

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


>
如果 RAMD_MAX 为32767,则 r10max 将具有32760的值。 32760到32767将被抛出,并且将获取一个新的随机值。

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.

这篇关于尝试一次取1个随机数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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