C/C++ STL之 #include 頭文件


在進行編程時,有時需要用到頭文件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.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM