用C语言实现,文件打开,程序用时,随机数生成

本文介绍如何使用C语言生成一个10*10的随机数矩阵,并将该矩阵保存到文本文件中。随机数范围设定在10到100之间。此外,还介绍了如何利用clock函数来测量整个生成过程的耗时。

用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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值