rand()从哪里得到数字

Where does rand() get its numbers from?

本文关键字:数字 rand      更新时间:2023-10-16

在做一个小项目时,我想我可以用一点这样的代码生成"随机"文件名,

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;