用随机数填充向量
Populating a vector with random numbers
我就直接开始吧:我的教授给了我一段代码,应该生成随机数,我的编译器(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;
}
相关文章:
- 用C++中的数字和条件填充向量
- 使用 C++98 标准填充二维静态向量
- 如何使用迭代器填充未知大小的向量?
- 使用 C++-17,如何从字符串向量填充元组
- 用基于范围的for循环填充指针向量
- 使用所述填充构造函数初始化向量中的向量
- 是否有可能让 c++ dll 在后台运行 python 程序并让它填充向量图?如果是这样,如何?
- 如何将目录中的文件属性填充到结构向量中?
- 有没有办法使用数组填充向量?
- 用对对填充向量未按预期工作
- 用于填充 Base 和派生对象的 shared_ptr 向量的函数模板
- 可选类输入中的 C++ 填充向量
- 用构造函数调用填充向量
- DLL – 在 DLL 初始化时填充的静态向量,向客户端程序返回零大小
- 从函数填充的字符串的推导向量到 int 的字符串
- parallel_for lambda 函数填充 2D 向量后出错
- 你能在C++中匿名填充一个向量向量吗?
- 如何有效地用向量填充结构
- 从矢量中擦除元素,并向量填充结构
- 一种用内部向量填充结构向量的优雅/高效方法