注册 登录
编程论坛 C语言论坛

生成随机数据程序

jklqwe111 发布于 2021-05-20 11:22, 1969 次点击
分享一个生成随机数据程序,适合为练习排序生成测试数据等,附件中含有exe程序 ,源码以及简要使用说明。以下是代码,欢迎讨论及提出改进意见
程序代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>  
#include <math.h>
#include <time.h>
#define N 100
#define RAND_MIN 0

int f(char* str,char* argv[],int n ,int*m)
{
   int i =0 ;
   char *p =NULL ;
     while(1)
     {
        if(i>=n)return -1 ;
        
        
        p=strstr(argv[i],str);
        if(p && (i+1<n))
        {
          *m=atoi(argv[i+1]) ;
          return 0    ;      
        }
        ++i;
     }         
}

int ff(char* argv[],int n ,int*m)
{
   int i =0 ;
   char *p =NULL ;
     while(1)
     {
        if(i>=n)return -1 ;
        p=strchr(argv[i],'/');
               
        if(p )
        {
          i+=2 ;  
        }
        else
        {
          *m=atoi(argv[i]) ;
          return 0    ;
        }
               
     }         
}
int main(int argc,char* argv[])
{  
  
  int  i , n , min  , max , line;
  unsigned int big ;
  double x ;
  n=N ;
  min=RAND_MIN ;
  max=RAND_MAX ;
  if(argc>1)
  
  {
      ff(argv+1,argc-1,&n) ;
      f("/min",argv+1,argc-1 ,&min) ;
      f("/max",argv+1,argc-1 ,&max) ;
  }
  printf("%d\n",n);
  srand(time(0)) ;
  
  for(i=0 ; i <n ; ++i)
  {
      unsigned int big =(unsigned int)(max-min) ;
      int s=0 ,k = 1 ;
      while(big!=0)
      {
          unsigned int big1=big%(RAND_MAX+1) ;
          big/=(RAND_MAX+1) ;
                    
          x = rand()/(RAND_MAX+1.0) ;
          s+= (int)(x * (big1+1.0))*k ;
          k*=(RAND_MAX+1) ;
        
      }
      printf("%d ",s+min);
      
    }
     printf("\n");
  return 0 ;
}




只有本站会员才能查看附件,请 登录
3 回复
#2
mindfulness2021-05-21 00:28
这个封装,实在没想出有什么特别能用的上的,毕竟stdlib已经有rand()了

    srand((int)time(NULL));
    s = rand();


我想了想,设计了一下,可以参考一下,这个API可能会好用一些
程序代码:

/*
@return, a random arry
@min~max: the range of the random result;
@type: the type of the random result,such as int float, char, and so on
@num: declare the num of the result random arry.
@....: if use the float, you may need give the information of accuracy
*/
void* create_random(void* min, void* max, char* type, int num,....);
#3
jklqwe1112021-05-21 08:52
这个程序只是扩大了rand的取值范围,没有别的功能,另外说明一下,这个程序是一个命令行小工具,不是用于编程的api,它的目的是为了方便在命令行工作时,生成一些数据使用,为什么会写它,是基于一下的原因,由于在ide下工作很多测试工作很不方便,因而尝试命令行中去做这些,在linux下 是有许多强大的工具的,比如rand也是有的,但是在windos中所能用的工具就太少了,对于有些不便,就尝试写些东西来用。
#4
mindfulness2021-05-23 05:59
回复 3楼 jklqwe111
嗯,可以理解。
由于windows下,各IDE的编译和运行环境各不相同,可能这个exe在其它PC上根本不能运行。
项目编程时,或许可以考虑将测试本身做成模块,用宏控制,而不是单独要另外exe的测试。
所以,窃以为,API+库的形式会比较适合常规意义上的小项目。
1