C中的随机数
我正在编写自己的方法来用 C 生成随机数,如下所示:
int randomNumber(){
int catch = *pCOUNTER;
int temp = catch;
temp /= 10;
temp *= 10;
return (catch - temp);
}
pCounter 基本上是指向我正在使用的设备中的寄存器的指针。该寄存器中的数字总是在增加,所以我的想法是只取第一个数字。
在某些时候,返回的数字变得大于 9,我不确定问题是出在我的代码中还是设备本身。该设备是 Altera DE1 板。
有人可以帮忙吗?
谢谢!
I'm writing my own method to generate a random number with C as follows:
int randomNumber(){
int catch = *pCOUNTER;
int temp = catch;
temp /= 10;
temp *= 10;
return (catch - temp);
}
pCounter
is basically a pointer to a register in the device I'm using. The number in that register is always increasing so my idea is to take the first digit only.
At some point, the number returned becomes larger than 9 and I'm not sure if the problem is in my code or the device itself. The device is an Altera DE1 board.
Can anyone please help with that?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您是否将
pCounter
声明为易失性?Did you declare
pCounter
as volatile?为了实现您在代码中尝试执行的操作:
但是,我怀疑这种方法是否接近合理随机......
To achieve what you're trying to do in your code:
However, I question if this approach is anywhere close to being reasonably random...
您确定不想使用 %= 代替 /= & *=?
Are you sure you're not looking to use %= instead of /= & *=?
我怀疑您的问题可能是编译器引入的“优化” - 如果您没有使用正确的波动性声明
pCOUNTER
,编译器可能会多次读取指针。我不知道您的处理器可能有多少个寄存器 - 如果寄存器中没有足够的寄存器来保存catch
,它可能会多次读取它(一次是为了获取一些东西来执行temp
) code> 计算,并再次计算最终返回值)。请尝试以下操作,这应确保
pCOUNTER
设备/寄存器仅被读取一次:I suspect that your problem might be an 'optimization' introduced by the compiler - if you don't have
pCOUNTER
declared with the correct volatility, the compiler could be reading through the pointer more than once. I have no idea how many registers your processor might have - if there's not enough to holdcatch
in a register, it might read it multiple times (once to get something to do thetemp
calculations on, and again for the final return value).Try the following, which should ensure that the
pCOUNTER
device/register is read exactly once:如果您正在寻找随机数字(仅限 0-9),请尝试对您的方法进行此修改。
但这并不是很随机。如果它总是在增加,大概以已知的速度增加,那么它是 100% 可预测的,根本不是随机的。
Altera 板上不允许使用
rand()
函数吗?编辑:
您始终可以编写自己的 PRNG。我在谷歌上搜索“简单的随机数生成器代码”,发现了几个简单的例子。最简单的如下:
If you're looking for a random digit (0-9 only), try this modification of your method.
This isn't very random, though. If it's always increasing, presumably at a known rate then it's 100% predictable, not random at all.
Is the
rand()
function not allowed on that Altera board?Edit:
You could always write your own PRNG. I did a Google search for "simple random number generator code", and found several simple examples. The simplest ones are along these lines:
如果你想任意将结果限制为 9:
我建议使用宏常量来抽象“10”,否则它就是一个幻数。
If you want to arbitrarily limit the result to 9:
I recommend using a macro constant to abstract the '10' though, otherwise it's a magic number.