- 需求: 输出[x,y]之间的随机数
- 算法: rand()%(y-x+1)+x
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> //交换函数 void swap(int *a, int *b){ int temp= 0; temp = *a; *a = *b; *b = temp; } //求两个随机数[20,40]数组的对应数组之和,存到第三个数组中。并且做冒泡排序。 int main(void){ int a[10] = {0}, b[10] = {0}, c[10] = {0}; int i = 0, j = 0; struct timeval timeNow; gettimeofday(&timeNow, NULL); srand(timeNow.tv_usec); //把当前时间, 微秒级别作为种子。 for (i = 0; i < 10; i++){ a[i] = rand()%21+20; b[i] = rand()%21+20; c[i] = a[i] + b[i]; printf("%d + %d = %d\n",a[i],b[i],c[i]); } printf("开始冒泡排序:\n"); for(i = 0; i< 10 -1; i++){ for(j = 0; j< 10 -1 -i; j++){ if(c[j] < c[j+1]) swap(&c[j], &c[j+1]); } } for(i = 0; i< 10; i++){ printf("c[%d] = %d\n",i,c[i]); } return 0; }
时间: 2024-11-10 12:56:43