(c语言版)使用随机函数rand

随机函数rand()详解

随机生成1-31号红球5个,随机生成1-16号白球2个,红球白球分别按照从小到大的顺序排序

c 复制代码
#include<stdio.h>
#include<stdlib.h>
int main() {
    int n = 0;
    int a[7] = {0};
    while (n < 5) {
        a[n++] = rand() % 32;
    }
    a[n++] = rand() % 17;
    a[n++] = rand() % 17;
    printf("随机生成的数字为:");
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    for(int i=0;i<4;i++){
        for(int j=0;j<4-i;j++){
            if(a[j]>a[j+1]){
                int t=a[j];
                a[j]=a[j+1];
                a[j+1]=t;
            }
        }
    }
    if(a[5]>a[6]){
        int t=a[5];
        a[5]=a[6];
        a[6]=t;
    }
    printf("排序后结果为:");
    for(int i=0;i<7;i++){
        printf("%d ",a[i]);
    }
    return 0;
}

标准写法

c 复制代码
#include<stdio.h>
#include<stdlib.h>
void getball(int *ball,int count,int base){          //count是要取走的球,编号为1-base
    int i=0;
    int a[31]={0};
    for(int i=0;i<base;i++){
        a[i]=i+1;
    }
    i=0;
    while(i!=count){
        int t=rand()%(31-i);
        ball[i]=a[t];
        a[t]=a[31-i-1];                      //最后一个球移过去,体现球的已取走
        i++;
    }
}
void sort(int a[],int n){
    for(int i=0;i<n;i++){
        for(int j=0;j<n-1;j++){
            if(a[j+1]<a[j]){
                int t=a[j];
                a[j]=a[j+1];
                a[j+1]=t;
            }
        }
    }
}
int main(){
    int ball[7]={0};
    getball(ball,5,31);
    getball(ball+5,2,16);
    sort(ball,5);
    sort(ball+5,2);
    for(int i=0;i<7;i++){
        printf("%d ",ball[i]);
    }
    return 0;
}
相关推荐
空山新雨(大队长)3 天前
C 语言第一课:hello word c
c++·c·exe
饭碗的彼岸one3 天前
C++ 并发编程:异步任务
c语言·开发语言·c++·后端·c·异步
EleganceJiaBao4 天前
我的创作纪念日
c
梁辰兴6 天前
数据结构:排序
数据结构·算法·排序算法·c·插入排序·排序·交换排序
charlie1145141917 天前
Windows 编程——字符串处理
windows·学习·c·字符串处理·windows编程
BlackQid8 天前
基于C的扫雷小游戏
游戏·c
牟同學9 天前
从竞态到原子:pread/pwrite 如何重塑高效文件 I/O?
linux·网络编程·c·多线程
studytosky11 天前
C语言数据结构之双向链表
c语言·数据结构·c++·算法·链表·c
BlackQid12 天前
基于C的二分查找和查月份天数小程序
算法·c
小牛历险记13 天前
手表--带屏幕音响-时间制切换12/24小时
c语言·开发语言·c·学习方法