rand()从哪里得到数字
Where does rand() get its numbers from?
在做一个小项目时,我想我可以用一点这样的代码生成"随机"文件名,
std::cout << "image"+rand()%255 << std::endl;
我得到的输出对我来说毫无意义。它们似乎是错误消息的随机部分。
例如这段代码:
int main()
{
while(1){
std::cout << "image" + rand() % 255 << std::endl;
}
return 0;
}
产生胡言乱语:
> ge
>
> n
>
>
> i
>
>
> ring too long
>
> U
>
>
>
>
>
> &
>
> n
> _
> o
> string position
> e
> lid string position
> i
>
>
>
>
> U
> g
> invalid string position
>
> U
> ing position
>
>
> &
>
>
>
>
> ring position
> !
> n
>
> oo long
>
>
>
>
>
> o
> position
以及QtCreator中一段更复杂的代码(主循环中有相同的cout和endl语句(
> atformmainwindow.cpp:210
>0
>I , null image received
>indow.cpp:210
>(QImage)
>dImage(QImage)
>, error: image not read from file!
> updatePlayerUI , null image received
>updatePlayerUI(QImage)
>ow.cpp:210
>dImage(QImage)
>ot chosen
>s not chosen
>og, error: image not read from file!
> was not chosen
>age not read from file!
>r: image not read from file!
>neDataPlatformmainwindow.cpp:210
>error: image not read from file!
这是什么原因?
"image"
的类型是const char*
,您在这里进行指针算术
"image" + rand() % 255
这(可能(是未定义的行为,因为您(可能(正在为该字符串分配的内存之外进行访问。要做你想要的
std::cout << "image" << (rand() % 255) << std:endl
或
std::cout << "image" + std::to_string(rand() % 255) << std:endl
"image" + rand() % 255
这个表达并不像你想象的那样。
您认为它的意思是"获取表达式rand() % 255
的结果,将其转换为字符串,并将其与字符串"image"
连接"。
它实际上意味着"将指针指向文字字符串"image"
,并将指针增加rand() % 255
个字符。">
当rand() % 255
的结果大于5(越界内存访问(时,这将导致未定义的行为。
在这种特殊情况下,编译器在生成的程序中将字符串文字值存储在彼此相邻的位置,因此递增指向字符串文字的指针将在该内存中移动并捕获随机字符串。
实现这一目标的正确方法是:
std::cout << "image" << (rand() % 255) << std::endl;
相关文章:
- 如何生成比用户使用 rand() 函数输入的数字大 5-10% 的数字?
- 为什么 rand() 给我的数字超出了我定义的间隔?(昨天工作正常)
- rand() 函数通过升序到前一个数字来生成下一个数字
- RAND()在递归功能中产生的数字高于设定范围
- 为什么rand()给出相对接近的数字
- 如何在使用随机生成器(srand,rand)时检查数字是否不同
- 如何使用RAND()在数组中生成数字
- rand()每次运行程序时都返回相同的数字
- 将 rand() 结果写入 C++ 文本文件,而不重复数字
- 如何直接获取rand()序列中的第n个数字,而不必调用rand(()n次
- 如何调用一个变量(包含rand()函数)并得到不同的数字
- rand() 生成相同的数字
- 为什么我的 rand() 数字显示为 0
- rand()生成器卡在1个数字c++上
- rand()不起作用,给了我一个超出指定的最大值和最小值的数字
- Rand从一个最大值为75的数字(36)开始时是如何工作的
- c++rand()和来自boost的RNG生成相同的数字(在发布模式中),即使srand(0)也是如此
- 为什么使用 rand() 会有更高数字的概率
- Rand() 是相同的数字生成器,即使我调用了 srand(time(NULL))
- 如何在C++中限制rand函数生成的数字