【问题标题】:Populating a vector with random numbers [closed]用随机数填充向量[关闭]
【发布时间】:2014-03-10 01:21:56
【问题描述】:

我将直接进入:我的教授给了我一段代码,该代码应该生成随机数,而我的编译器 (g++) 不断抛出这些错误:“警告:指向算术中使用的函数的指针 [- Wpointer-arith] rand[i]=((double) rand() / (static_cast(RAND_MAX) + 1.0))* (high - low) + low;" “错误:从类型 'std::vector' 到类型 'double' 的无效转换 rand[i]=((double) rand() / (static_cast(RAND_MAX) + 1.0))* (high - low) + low;” 它们都指向生成随机数的函数。问题是我以前用过这个完全相同的功能,而且效果很好。我真的不知道可能出了什么问题。任何帮助将不胜感激。请注意,我对 C++ 还有些陌生。

我已包括:cstdlib、stdio.h、cstdio、time.h、vector、iomanip、fstream、iostream、cmath。 这是我现在拥有的代码:

int main() {
int N=20000;

std::srand((unsigned)time(0));

for(int i = 0; i<(N+1); ++i) {
    double high = 1.0, low = 0.0;
    rand[i]=((double) rand()/(static_cast<double>(RAND_MAX) + 1.0))*(high - low) + low;
    }

return 0;
}

【问题讨论】:

  • 错字?问题是 rand[i] ... rand 是一个函数而不是一个数组。一旦你解决了这个问题,你应该会很好。
  • 确实,您将rand 用作函数和数组
  • 相关:如果可能,请认真考虑使用&lt;random&gt; 库。 It really is the cat's whiskers.
  • 啊,谢谢!修好了,检查了数字,一切看起来都很好!

标签: c++ random


【解决方案1】:

您将名称rand 用作要写入的数组和调用的标准库函数。那很糟。

用其他名称声明一个数组,然后写入它。例如:

int main() {
  int N=20000;

  std::srand((unsigned)time(0));
  std::vector<double> A(N+1);

  for(int i = 0; i<(N+1); ++i) {
    double high = 1.0, low = 0.0;
    A[i]=((double) rand()/(static_cast<double>(RAND_MAX) + 1.0))*(high - low) + low;
  }

  return 0;
}

【讨论】:

  • 谢谢,效果很好 - 也检查了数字,一切看起来都很棒。再次感谢!
【解决方案2】:

真的是超越兰特的时候了。这是使用 C++11 中的功能的更现代的版本。

#include <algorithm>
#include <iterator>
#include <random>
#include <vector>

int main()
{
    const int n = 20000;

    std::random_device rd;
    std::mt19937 e(rd());        // The random engine we are going to use

    const double low = 0.0;
    const double high = 1.0;

    std::uniform_real_distribution<double> urng(low, high);

    std::vector<double> A;
    std::generate_n(std::back_inserter(A), n + 1,
        [urng, &e](){ return urng(e); });

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多