C/C++ STL之 #include <cstdlib>头文件

在进行编程时,有时需要用到头文件cstdlib中的方法,cstdlib中方法有如下类型:

<1>  字符串转换

atof: 字符串转浮点型;atoi:字符串转整型;atol:字符串转长整型

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

int main ()
{
  char str[] = "256";
  int f_result, i_result, l_result;
  // 字符串转浮点型
  f_result = atof(str);
  printf("%d\n", f_result);
  
  // 字符串转整型
  i_result = atoi(str);
  printf("%d\n", i_result);
  
  // 字符串转长整型
  l_result = atol(str);
  printf("%d\n", l_result);
  return 0;
}
执行结果:
256
256
256

<2> 伪随机序列生成

rand: 产生随机数

srand:初始化随机因子,防止随机数总是固定不变

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

int main ()
{
  int n, n1, n2, n3;

  /* initialize random seed: */
  srand (time(NULL));
  /* generate secret number between 1 and 2147483647: */
  n = rand();
  printf("%d\n", n);
  
  /* generate secret number between 1 and 10: */
  n1 = rand() % 10 + 1;
  printf("%d\n", n1);
  
  /* generate secret number between 1 and 100: */
  n2 = rand() % 100 + 1;
  printf("%d\n", n2);
  
  /* generate secret number between 1 and 1000: */
  n3 = rand() % 1000 + 1;
  printf("%d\n", n3);
  return 0;
}
执行结果:
425153669
7
71
228

<3> 动态内存管理

calloc, malloc,realloc, free

#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* malloc, free, rand */

int main ()
{
  
  int i,n;
  char * buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &i);

  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)
    buffer[n]=rand()%26+'a';
  buffer[i]='\0';

  printf ("Random string: %s\n",buffer);
  free (buffer);
  
  int  * buffer1, * buffer2, * buffer3;
  buffer1 = (int*) malloc (100*sizeof(int));
  buffer2 = (int*) calloc (100,sizeof(int));
  buffer3 = (int*) realloc (buffer2,500*sizeof(int));
  free (buffer1);

  return 0;
}
输入:13
输出:How long do you want the string? Random string: nwlrbbmqbhcda

<4> 整数运算

abs

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

int main ()
{
  int n,m;
  n=abs(23);
  m=abs(-11);
  printf ("n=%d\n",n);
  printf ("m=%d\n",m);
  return 0;
}
n=23
m=11

div

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

int main ()
{
  div_t divresult;
  divresult = div (38,5);
  printf ("38 div 5 => %d, remainder %d.\n", divresult.quot, divresult.rem);
  return 0;
}
执行结果:
38 div 5 => 7, remainder 3.

 

posted on 2020-06-02 15:34  天池怪侠  阅读(2109)  评论(0编辑  收藏  举报

导航