您的位置:首页 > 编程语言 > C语言/C++

c语言 伪 随机数 小结

2015-02-13 18:31 169 查看
需求: 输出[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;
}


本文出自 “帝国金菜园子” 博客,请务必保留此出处http://diguojin.blog.51cto.com/5034509/1614373
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: