【问题标题】:rand() in MinGW g++MinGW g++ 中的 rand()
【发布时间】:2017-01-03 07:13:18
【问题描述】:

我有一个像这样的基本 C++ 文件:

#include <iostream>

using namespace std;

int main() {
    float x = rand();
    cout << x << endl;
    return 0;
}

当我使用 g++ test.cpp -o test -std=c++11 在 Ubuntu 上通过 g++ 运行它时,我没有收到任何错误,并且程序运行得很好。但是当我使用相同的命令在 MinGW 上通过 g++ 运行它时,我收到以下错误:

test.cpp: In function 'int main()':
test.cpp:6:17: error: 'rand' was not declared in this scope
  float x = rand();
                 ^

我有 GCC 版本 5.3.0。尝试使用 g++ test.cpp -o test.exe -std=gnu++11g++ test.cpp -o test.exe -std=c++0x 进行编译会产生相同的结果。

【问题讨论】:

  • 你可以尝试添加 吗?
  • @coderredoc rand_s() 产生与以前相同的结果。 @D_Untouchable 包括&lt;cstdlib&gt;rand() 确实“有效”,但其他C++11 函数如time(NULL) 仍然无法正常工作。我认为 MinGW 的 C++11 支持完全被破坏了。再一次,g++11c++0x 给了我同样的东西。
  • 更正:time(NULL) 不是 C++11 函数,但在 MinGW 中也绝对不能工作。
  • @Sil.: 问题是如前所述的标题包含...检查 mingw 编译器的组件
  • 我知道 中的 rand() 函数,但它不是我需要的。我特别需要 rand() 函数在 C++11 标准中可用,而不包括在 C++98 标准中也可用的标头。换句话说,我需要 g++ 在 Linux 和 Windows 上以相同的方式工作。这很关键。有什么方法可以安装更接近其 Linux 版本的 g++ 版本,还是完全放弃 MinGW 对我来说是一个更好的主意?

标签: c++ c++11 mingw


【解决方案1】:

您必须首先包含随机函数的库

#include < cstdlib >

之后您的代码将完美运行

这是正确的代码

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
float x = rand();
cout << x << endl;
return 0;
}

一些编译器允许您使用随机函数而不包括库,但标准 C++ 编译器不允许您使用。 希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2023-03-04
    • 2014-09-03
    • 1970-01-01
    相关资源
    最近更新 更多