c语言实现随机整数抽取

        用c语言实现以下功能:例如给定1000,从其中随机抽取10个数(不重复),本程序可实时输入总个数和抽样个数,最终抽取的数字保存在‘D:\sampling_number.txt’中。

 

#include <stdio.h>
#include <stdlib.h>
#include<time.h>
#include<math.h>

void swap2(int *,int *);
void bubble(int storenumber[ ],int n);

int storenumber[100000]={0};  /*the max number of sampling is 100000*/

int main()
{
	FILE *f1;

	double p;
	int h,k,i;
	int N,Nsample,number;
	char anything;
    srand((unsigned)time(NULL));
    printf("Enter the total number:\n");
    scanf("%d",&N);
    printf("Enter the sampling size:\n");
    scanf("%d",&Nsample);


    for(h=1;h<=Nsample;h++){
        p=rand()/(double)(RAND_MAX);
        number=(int)(p*N)+1;
        for(k=1;k<=h;k++){         /*remove the duplicate number*/
            if(number==storenumber[k]){
                p=rand()/(double)(RAND_MAX);
                number=(int)(p*N)+1;
                k=0;
            }
        }

        storenumber[h]=number;
    }

    printf("\n MAKE A FORTUNE, LEO!!!\n\n");

    bubble(storenumber,Nsample);   /*for the numeric sorting*/


    if((f1=fopen("d:\\sampling_number.txt","w"))==NULL){
        printf("file open error!\n");
        exit(0);
    }

    for(i=1;i<=Nsample;i++){
        fprintf(f1,"%d\n",storenumber[i]);
        printf("The %d sample is %d\n",i,storenumber[i]);
    }

    if(fclose(f1)){
        printf("can not close the file!\n");
        exit(0);
    }

    printf("\n ATTENTION:\n The file is saved in 'D:\\sampling_number.txt' \n");
    printf("\n Type any character on keyboard,  then 'Enter'");
    scanf("%s",&anything);

    return 0;
}


void bubble(int storenumber[ ],int n)         /*for the numeric sorting*/
{
    int i,j;
    for(i=1;i<=n;i++){
        for(j=1;j<=n-i;j++){
            if(storenumber[j]>storenumber[j+1]){
                swap2(&storenumber[j],&storenumber[j+1]);
            }
        }
    }
}

void swap2(int *px,int *py)
{
    int t;
    t=*px;
    *px=*py;
    *py=t;
}

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值