- 帖子
- 7
- 精华
- 0
- 积分
- 79
- 阅读权限
- 20
- 注册时间
- 2013-12-12
- 最后登录
- 2014-1-10
|
回帖奖励 +5
本帖最后由 xuefu 于 2013-12-17 00:59 编辑
第一次发现C标准库里还有排序的函数。。。- #include <assert.h>
- #include <stdio.h>
- #include <stdlib.h>
- int compare_ascending(const void* a, const void* b)
- {
- return (*(int*)a - *(int*)b);
- }
- int main(int argc, const char *argv[])
- {
- int a, n, m, i = 0, j = 0;
- int* secret;
- printf("Input n: ");
- scanf("%d", &n);
- assert(n > 1 || n == 1);
- printf("Input m: ");
- scanf("%d", &m);
- if(m > 0 && !(m > n))
- printf("Below is the number: \n");
- else
- {
- printf("the number m should be greater than zero and not larger than n.\n");
- exit(0);
- }
- secret = malloc(sizeof(int) * m);
- srand(time(NULL));
- while(m--)
- {
- /* generate the number you want */
- while(1)
- {
- a = rand() % n + 1;
- /* check a whether is repeated */
- for(j = 0; j < i; j++)
- {
- if(a == secret[j])
- {
- a = 0;
- break;
- }
- }
- if(a != 0)
- break;
- }
- secret[i++] = a;
- }
- qsort(secret, i, sizeof(int), compare_ascending);
- for (j = 0; j < i; j++)
- printf("%d ", secret[j]);
- printf("\n");
- free(secret);
- return 0;
- }
复制代码 |
|