【问题标题】:Where does rand() get its numbers from? [closed]rand() 从哪里得到它的数字? [关闭]
【发布时间】:2015-07-16 16:05:32
【问题描述】:

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

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 rand endl 语句)

>    atform\mainwindow.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!
>neDataPlatform\mainwindow.cpp:210
>error: image not read from file!

这是什么原因?

【问题讨论】:

  • 仅供参考:不再建议使用 rand()。请改用 库。
  • 这个问题没有得到很好的研究。你不能只是把一些你不理解的非常复杂的东西全部扔到一个问题中。您应该尝试缩小问题范围并将其隔离。例如,您可以/应该先尝试std::cout &lt;&lt; "image"+10 &lt;&lt; std::endl;,看看它是否符合您的想法,然后再考虑rand()

标签: c++ random iostream cout


【解决方案1】:

"image"的类型是const char*,你这里是做指针运算

"image" + rand() % 255

这是(可能)未定义的行为,因为您(可能)在为该字符串分配的内存之外访问。做你想做的事

std::cout << "image" << (rand() % 255) << std:endl    

或者

std::cout << "image" + std::to_string(rand() % 255) << std:endl

【讨论】:

  • Ehm 或者只是 "image" &lt;&lt; (rand() % 255),这样会更明智....
  • 好的,所以
  • @LightnessRacesinOrbit 当然,我只是想说明为什么他们的原始代码不起作用
  • @Lightness 是的,我没有使用那个代码,当我看到奇怪的输出时我只是好奇
  • @CoryKramer: 当然,我只是想提出一个更好的建议来修复它:) 字符串构造的魔力(以及这种有效的const char*->std::string coercion ) 对于这个特定问题来说似乎太多了。
【解决方案2】:
"image" + rand() % 255

这个表达式并不像你想象的那样。

你认为它的意思是“获取表达式rand() % 255的结果,将其转换为字符串,并与字符串"image"连接”。

它实际上的意思是“将指针指向文字字符串"image",并将该指针增加rand() % 255 个字符。”

rand() % 255 的结果大于 5(越界内存访问)时,这会导致未定义的行为。

在这种特殊情况下,您的编译器在生成的程序中将字符串文字值存储在彼此附近,因此递增指向字符串文字的指针将在该内存中移动并捕获随机字符串。

实现这一点的正确方法是:

std::cout << "image" << (rand() % 255) << std::endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多