(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;
}
相关推荐
乖乖是干饭王8 小时前
Linux 内核 Kbuild 中的 ld 调用机制
linux·c·makefile
SmoothSailingT13 小时前
C/C++与C#——指针的作用
开发语言·c++·c
程芯带你刷C语言简单算法题2 天前
Day30~实现strcmp、strncmp、strchr、strpbrk
c语言·学习·算法·c
xlp666hub2 天前
手写 Linux 并发服务器,fork, pthread与 epoll 模型实战(包含深层原理剖析)
github·c
charlie1145141913 天前
在上位机上熟悉FreeRTOS API
笔记·学习·嵌入式·c·freertos·工程
liu****4 天前
二.protobuf的使用
c++·c·protobuf·企业级组件
程芯带你刷C语言简单算法题6 天前
Day28~实现strlen、strcpy、strncpy、strcat、strncat
c语言·c++·算法·c
FOX69 天前
C语言作业(课本C97)
c
Jerry丶Li9 天前
三十八、W25Q64简介
stm32·嵌入式硬件·c
雪域迷影9 天前
macOS中使用cJSON解析库解析JSON
c++·macos·json·c·cmake·pkg-config