我正在尝试在 C++ 中使用 rand() 函数,但它每次都返回相同的随机数。
我已将语句srand(unsigned int(time(0)));
放在 main 函数的第一行,但我仍然遇到这个问题。
我用谷歌搜索了这个问题,并在这个网站上找到了几个答案,但他们都建议将srand()
语句放在 main 函数的第一行,我已经这样做了。
有没有人可以帮我解决这个问题?谢谢。
编辑@下午 5:10:
该程序是一个复杂的程序。我试图排除故障,这里有一些附加信息:
主要功能:
int main(int argc, char **argv) {
srand(time(0));
std::auto_ptr<simulation> sim_ptr;
const double delta_t = 0.000002;
if (argc != 2) {
std::cerr << "Error: invalid number of arguments specified" << std::endl;
exit(EXIT_FAILURE);
} else if (strcmp(argv[1], "--random") == 0) {
sim_ptr = std::auto_ptr<simulation>(create_random_simulation(delta_t));
} else if (strcmp(argv[1], "--naive") == 0) {
const double alpha = 1000;
sim_ptr = std::auto_ptr<simulation>(create_naive_simulation(delta_t, alpha));
} else if (strcmp(argv[1], "--tree") == 0) {
const double alpha = 1000;
sim_ptr = std::auto_ptr<simulation>(create_tree_simulation(delta_t, alpha));
}
const size_t time_steps = 200;
const size_t particles_count = 2048;
const size_t particles_shown = 2048;
const size_t image_width = 512;
const size_t image_height = 512;
std::valarray<double> m = random_valarray(particles_count);
m = m * m * m;
std::valarray<double> x = random_valarray(particles_count);
std::valarray<double> y = random_valarray(particles_count);
std::valarray<double> vx, vy;
vx.resize(particles_count);
vy.resize(particles_count);
std::cout << "Simulation" << std::endl;
for (size_t time_step = 1; time_step <= time_steps; time_step++) {
std::cout << "\tFrame " << time_step << " / " << time_steps << std::endl;
sim_ptr->step(x, y, vx, vy, m);
std::vector<uint8_t> image;
image.resize(image_width * image_height);
for (size_t particle = 0; particle < particles_shown; particle++) {
const uint8_t color = ((particle * 23297) % 255) + 1;
draw_particle(x[particle], y[particle], m[particle], &image[0], image_width, image_height, color);
}
const std::string image_path = get_image_path(time_step);
write_bmp_image(image_path, &image[0], image_width, image_height);
}
return 0;
}
调用每次为零的 rand() 的类函数:
void random_simulation::step(std::valarray<double>& x, std::valarray<double>& y,
std::valarray<double>& vx, std::valarray<double>& vy,
std::valarray<double>& m) const
{
const size_t particles_count = x.size();
assert(particles_count == y.size());
assert(particles_count == vx.size());
assert(particles_count == vy.size());
const double tau = 2.0 * sqrt(2.0 * this->delta_t);
for (size_t i = 0; i < particles_count; i++) {
x[i] = x[i] + tau * (((rand() % 2001 - 1000)/2000));
y[i] = y[i] + tau * (((rand() % 2001 - 1000)/2000));
if (i == 1){
std::cout << x[i] << " ";
std::cout << y[i] << " ";
}
}
}
simulation* create_random_simulation(double delta_t) {
return new random_simulation(delta_t);
}
根据循环,x[i]
并且y[i]
应该随着每次迭代而改变,但它们在每次迭代中保持不变。