用C语言生成文本文件,内容为10*10的随机数矩阵,其中随机数范围为[10-100],并计算用时。其中有很多需要注意的地方
#include
#include
#include
#define PATH "/home/deropty/cache/test.txt" //"~/cache/test.txt" will not work
#define MAXNUM 100
#define MINNUM 10
int main()
{
int i, j;
clock_t start, finish; //clock numbers
FILE *fp = NULL; //!!!
fp = fopen(PATH, "w");
if(fp == NULL){ //sometimes it is useful
printf("cannot open this file, oops!\n");
return 0;
}
//provides the random seed,
//otherwise produces the same results
srand((int)time(NULL));
start = clock();
for(i = 0; i < 10; i ++){
for(j = 0; j < 10; j ++){
fprintf(fp, "%3d", rand()%(MAXNUM-MINNUM) + MINNUM);
}
fprintf(fp, "\n");
}
finish = clock();
printf("input the file takes %f seconds\n",
(double)(finish-start) / CLOCKS_PER_SEC);
fclose(fp); //a good sytle
fp = NULL;
return 0;
}
本文介绍如何使用C语言生成一个10*10的随机数矩阵,并将该矩阵保存到文本文件中。随机数范围设定在10到100之间。此外,还介绍了如何利用clock函数来测量整个生成过程的耗时。

986

被折叠的 条评论
为什么被折叠?



