【发布时间】:2020-07-25 22:15:28
【问题描述】:
我正在尝试开发一维随机游走模拟。我正在沿着一条具有 10 个粒子可以占据的离散位置的线对粒子进行建模。粒子每次“跳跃”时只能向左或向右移动一格。在这个模拟中,我得到了解释 20 跳的代码。在执行每个“跳跃”以告诉“粒子”向左或向右移动之前,随机数生成器会产生 0 - 代表左侧和 1 - 代表右侧。请参阅下面的代码和进一步的 cmets。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int randomInt( int max); // declaration of function //
int main()
{ // declaration of variables //
int i, j = 0;
int totalHops=20;
int seed;
int sites[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *location;
location = &sites[j];
seed = time(NULL);
printf("The seed value for this 'random walk' is: %d.\n\n", seed); //keeping track of the seed used//
// setup the random number generator //
srandom(seed); // random path sequence //
printf("Initial location of the particle is at site %d.\n\n", *location);
for ( i=1; i<totalHops+1; i++ )
{
int direction = randomInt(2); // Two possible directions for particle to move, 0 = left, 1 = right //
if (direction == 1) {
location+= 1; // pointer moves right one space on array //
}
else {
location-= 1; // pointer moves left one space on array //
}
printf("After %2.d hop(s), the particle is at site %d.\n", i, (*location)%10); // I would prefer to be printing the entry of my array rather than relying on the fact the array is lablled with each entry the positon I have changed the pointer to //
}
printf("\n");
}
// function definition //
int randomInt(int max)
{
return (random() % max);
}
每次我的输出都不是我所期望的那种模式。例如,它似乎输出粒子在一次迭代中处于位置 0,而在下一次迭代中突然处于位置 4。我宁愿打印站点 [] 数组的条目,而不是在每个条目中输入位置并打印指针的值。
如果有人在这里提供帮助,我将不胜感激。我是指针的新手,所以任何帮助将不胜感激。
【问题讨论】:
-
请重新表述您的问题,使其更简洁、更通用,以便更容易回答,并造福后代
-
time()的返回类型是time_t。你的int可能太小了。这也意味着:打开编译器的警告!
标签: c arrays pointers random-seed random-walk