用随机数填充向量

Populating a vector with random numbers

本文关键字:向量 填充 随机数      更新时间:2023-10-16

我就直接开始吧:我的教授给了我一段代码,应该生成随机数,我的编译器(g++)一直抛出这些错误:"警告:指向算术中使用的函数的指针[- wpointer -arith] rand[I]=((double) rand()/(static_cast(RAND_MAX) + 1.0))*(高-低)+低;"错误:从'std::vector'类型转换为'double'类型rand[i]=((double) rand()/(static_cast(RAND_MAX) + 1.0))*(高-低)+低;"它们都指向生成随机数的函数。问题是我以前用过同样的函数,效果很好。我真的不知道哪里出了问题。任何帮助都将非常感激。注意,我对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作为要写入的数组和要调用的标准库函数。这是不好的。

声明一个其他名称的数组,并写入它。如:

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;
}

真的是时候超越rand了。这是一个更现代的版本,使用了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;
}