关于time( ) 函数在srand( ) 函数 中的应用有关问题,随机选数
关于time( ) 函数在srand( ) 函数 中的应用问题,随机选数

------解决方案--------------------
time(0)返回的是从1979年1月到今的秒数,如果你的程序在1秒之内可以运行完毕,则每次循环time(0)的返回值相同,所以造成随机序列是相同的,也就是如你看到的输出值相同。如果你的程序运行时间会超过1秒,你就可看到不同的输出值了。比如,你把lim取值为1000000,你会看到不同的输出值。
------解决方案--------------------
time函数返回了从1970.1.1 0:0到当前的秒数。
理论上来说,只要你单步调试的够快,还是会返回一样的结果的
放在循环里运行的话,time返回的值一般是同一个,除非过了一秒
# include <stdio.h>
# include <stdlib.h> // 提供srand () 和 rand () 函数;
# include <time.h> // 提供time () 函数;
# define SIZE 40
void rand_print (int ar[], int n, int limit);
void gene_array (int ar[], int n);
int main (void)
{
int array[SIZE];
int lim;
gene_array (array, SIZE);
puts ("enter the limit of number:");
while (scanf ("%d", &lim) == 1)
{
rand_print (array, SIZE, lim);
puts ("next.");
}
return 0;
}
void rand_print (int ar[], int n, int limit) // 在for循环中随机生成被选数的索引号,
{ //但是有个有趣的现象,每次输入挑选的数目,
int order, index; // 显示出来的数都是一样,
for (order = 0; order < limit; order++) // 然而在单步调试中,与期望的一样,挑选出的不同的值,
{ // 我想问的是,难道因为for循环处理就是在一瞬之间,所以
srand ((unsigned int)time (0)); // time得到系统时间每次都一样?
index = rand () % n ; // 而我单步调试,手动执行每次肯定都不一样!
printf ("%5d", ar[index]);
if (order % 5 == 4)
putchar ('\n');
}
if (order % 5 != 0)
putchar ('\n');
}
void gene_array (int ar[], int n)
{
int i;
for (i = 0; i < n; i++)
ar[i] = i * 2 + 1;
}
------解决方案--------------------
time(0)返回的是从1979年1月到今的秒数,如果你的程序在1秒之内可以运行完毕,则每次循环time(0)的返回值相同,所以造成随机序列是相同的,也就是如你看到的输出值相同。如果你的程序运行时间会超过1秒,你就可看到不同的输出值了。比如,你把lim取值为1000000,你会看到不同的输出值。
------解决方案--------------------
time函数返回了从1970.1.1 0:0到当前的秒数。
理论上来说,只要你单步调试的够快,还是会返回一样的结果的
放在循环里运行的话,time返回的值一般是同一个,除非过了一秒