Xiao bailong

一个用C语言的大一题目。

利用matlab(或其他任何方式)生成100个随机数,并编制C语言程序进行从

小到大排序。

1、生成的随机数必须存放在文件中(.txt),在程序中读取文件数据(文件操作)

2、利用子函数实现排序算法(任意排序算法均可),在主函数中调用(函数调用)

3、必须利用指针存放数据,进行排序操作(指针操作)

 

因为好久没有学习C语言了。所以忘记了许多。在室友的帮助下,虽然他的脑子还是有点zou.有些时候还会咆哮,不懂得安静,所以很多问题都没有解决,

但是最后的代码还是处理了。具体代码如下。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h> 
 4 
 5 int genrand(long , char);
 6 void sort(long *p, int num);
 7 
 8 void main()
 9 {
10     char file[9] = "send.txt";
11     int num = 10;
12     int a = 0;
13     genrand(10,file);
14 
15     if (a==0)
16     {
17         printf("写入成功");
18     }
19 
20     getchar();
21 }
22 
23 int genrand(long num, char *file)
24 {
25     long te;
26     int x, y;
27     long *dat = (long *)malloc(num * sizeof(long));
28     long *p=dat, i;
29 
30 
31 
32 
33 
34     if (dat == NULL){
35         printf("malloc error, memory not enough!\n");
36         exit(1);
37     }
38 
39     srand((unsigned int)time(0));
40     for (i = 0; i < num; i++){
41         dat[i] = rand()%50;
42     }
43 
44     sort(dat, num);
45     
46     /* 保存到文件中 */
47     FILE *fp = fopen(file, "w");
48     if (fp == NULL){
49         printf("fopen error, can't open file %s!\n", file);
50         exit(2);
51     }
52 
53     while (num--){
54         fprintf(fp, "%ld\n", *p++);
55     }
56     free(dat);
57     fclose(fp);
58     return 0;
59 }
60 
61 void sort(long *p , int num)
62 {
63     long te;
64     int x, y;
65     for ( x = 0; x < num-1; x++)
66     {
67         for ( y = num-1; y>x ; y--)
68         {
69             if (p[y]<p[y-1])
70             {
71                 te = p[y-1];
72                 p[y-1] = p[y];
73                 p[y] = te;
74             }
75         }
76     }
77 }
算法代码

 

posted @ 2015-05-22 21:39  小白龙on  阅读(954)  评论(0)    收藏  举报

QQ:846650266,电话:15117424475

© 白龙工作室 |隐私条款 |服务条款 |盘ICP备10000000号-1