标准库函数部分简述

来源:互联网 发布:c语言主要特点 编辑:程序博客网 时间:2024/05/21 05:44

一、整形函数

1.算术 <stdlib.h>

#include <stdio.h>#include <stdlib.h>int main(){div_t result;   //因为函数div返回类型为div结构result = div(8,5);   //第二个参数(分母)除以第一个参数(分子)printf("%d,%d\n",result.quot,result.rem);   //quot作为商,rem作为余数return 0;}

2.随机数  <stdlib.h>

#include <stdio.h>#include <stdlib.h>#include <time.h>#define TRUE 1#define FALSE 0void shuffle(int  *deck,int n_cards){int i;static int first_time = TRUE;//若尚未初始化,用当前时间进行初始化if(first_time){first_time = FALSE;srand((unsigned int)time(NULL));}//通过交换随即对的牌进行“洗牌”for (i = n_cards - 1;i > 0;i--){int where;int temp;where = rand() % i;printf("%d\t",rand());temp = deck[where];deck[where] = deck[i];deck[i] = temp;}}int main (){int arry[] = {1,2,3,4,5,6,7,8,9,0};shuffle(arry,10);for (int *p = arry;p < arry + sizeof(arry)/sizeof(int);p++)printf("%d ",*p);printf("\n");return 0;}

运行结果如下:


3.字符串转换<stdlib.h>

int atoi ( const char * str );//Convert string to integer
long int atol ( const char * str )//Convert string to long integer
long int strtol ( const char * str, char ** endptr, int base );//Convert string to long integer
unsigned long int strtoul ( const char * str, char ** endptr, int base );//Convert string to unsigned long integer

#include <stdio.h>#include <stdlib.h>int main (){int i;char szInput [256];printf ("Enter a number: ");fgets ( szInput, 256, stdin );i = atoi (szInput);printf ("The value entered is %d. \n",i);return 0;}

二、浮点型函数

1.三角函数<math.h>

2.双曲函数<math.h>

3.对数和指数函数<math.h>

4.浮点表示形式<math.h>

5.幂<math.h>

6.底数、顶数、绝对值和余数<math.h>

7.字符串转换<stdlib.h>

三、日期和时间函数

1.处理器时间<time.h>

clock_t clock ( void );//clock函数返回程序开始执行起处理器所消耗的时间
Clock program
Returns the number of clock ticks elapsed since the program was launched.

The macro constant expression CLOCKS_PER_SEC specifies the relation between a clock tick and a second (clock ticks per second).

The initial moment of reference used by clock as the beginning of the program execution may vary between platforms. To calculate the actual processing times of a program, the value returned by clock should be compared to a value returned by an initial call to clock.

Parameters

(none)

Return Value

The number of clock ticks elapsed since the program start.

On failure, the function returns a value of -1.

clock_t is a type defined in <ctime> to some type capable of representing clock tick counts and support arithmetical operations (generally a long integer).

Example

1234567891011121314151617181920212223
/* clock example: frequency of primes */#include <stdio.h>#include <time.h>#include <math.h>int frequency_of_primes (int n) {  int i,j;  int freq=n-1;  for (i=2; i<=n; ++i) for (j=sqrt(i);j>1;--j) if (i%j==0) {--freq; break;}  return freq;}int main (){  int f;  int t;  printf ("Calculating...\n");  f = frequency_of_primes (99999);  t = clock();  printf ("The number of primes lower than 100,000 is: %d\n",f);  printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);  return 0;}


Output:
Calculating...The number of primes lower than 100,000 is: 9592It took me 143 clicks (0.143000 seconds).

2.当天时间<time.h>

time_t time ( time_t * timer );//time函数返回当前日期和时间
Get current time
Get the current calendar time as a time_t object.

The function returns this value, and if the argument is not a null pointer, the value is also set to the object pointed by timer.

Parameters

timer
Pointer to an object of type time_t, where the time value is stored.
Alternativelly, this parameter can be a null pointer, in which case the parameter is not used, but a time_tobject is still returned by the function.

Return Value

The current calendar time as a time_t object.

If the argument is not a null pointer, the return value is the same as the one stored in the location pointed by the argument.

If the function could not retrieve the calendar time, it returns a -1 value.

Example

12345678910111213
/* time example */#include <stdio.h>#include <time.h>int main (){  time_t seconds;  seconds = time (NULL);  printf ("%ld hours since January 1, 1970", seconds/3600);    return 0;}


Possible output:
266344 hours since January 1, 1970


3.日期和时间的转换<time.h>

char * ctime ( const time_t * timer );//ctime函数的参数是一个指向time_t的指针,并返回一个指向字符串的指针
Convert time_t value to string
Converts the time_t object pointed by timer to a C string containing a human-readable version of the corresponding local time and date.

The returned string has the following format:

Www Mmm dd hh:mm:ss yyyy 
Where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year.

The string is followed by a new-line character ('\n') and the terminating null-character.

This function is equivalent to: asctime(localtime(timer)).

Parameters

timer
Pointer to a time_t object that contains a calendar time.

Return Value

A C string containing the date and time information in a human-readable format.

The array which holds this string is statically allocated and shared by both the ctime and asctime functions. Each time either one of these functions is called the content of this array is overwritten.

Example

12345678910111213
/* ctime example */#include <stdio.h>#include <time.h>int main (){  time_t rawtime;  time ( &rawtime );  printf ( "The current local time is: %s", ctime (&rawtime) );    return 0;}


Output:

double difftime ( time_t time2, time_t time1 );//计算time_1- time_2的差,并把结果转换为秒
Return difference between two times
Calculates the difference in seconds between time1 and time2.

Parameters

time2
time_t object representing the latter of the two times.
time1
time_t object representing the earlier of the two times.

Return Value

The difference in seconds (time2-time1) as a floating point double.

Example

1234567891011121314151617181920
/* difftime example */#include <stdio.h>#include <time.h>int main (){  time_t start,end;  char szInput [256];  double dif;  time (&start);  printf ("Please, enter your name: ");  gets (szInput);  time (&end);  dif = difftime (end,start);  printf ("Hi %s.\n", szInput);  printf ("It took you %.2lf seconds to type your name.\n", dif );   return 0;}


Output:



四、执行环境

1.中止执行<stdlib.h>

void abort ( void );

Abort current process
Aborts the process with an abnormal program termination.
The function generates the SIGABRT signal, which by default causes the program to terminate returning anunsuccessful termination error code to the host environment.

The program is terminated without executing destructors for objects of automatic or static storage duration, and without calling any atexit function.

The function never returns to its caller.

Parameters

(none)

Return Value

(none)

Example

#include <stdio.h>#include <stdlib.h>int main(){FILE *file;file = fopen("test.txt","r");if (file == NULL){perror("cannot open the file!");abort();}else//此处的else不可少,不然当要打开文件不存在时会引发错误fclose(file);return 0;}

2.断言<assert.h>

void assert (int expression);//assert只是用验证为真的表达式

当程序完整测试完以后,可在编译时通过定义NDEBUG消除所有的断言。在定义NDEBUG以后,预处理器将丢弃所有的断言,就减小了这方面的

开销,而不必在源文件中把所有断言实际删除。

/* assert example */#include <stdio.h>#include <assert.h>void print_number(int* myInt) {assert (myInt!=NULL);printf ("%d\n",*myInt);}int main (){int a=10;int * b = NULL;int * c = NULL;b=&a;print_number (b);print_number (c);//assert在此处发生运行错误return 0;}

3.环境<stdlib.h>

4.执行系统命令<stdlib.h>

int system ( const char * command );
Execute system command
Invokes the command processor to execute a command. Once the command execution has terminated, the processor gives the control back to the program, returning an int value, whose interpretation is system-dependent.

The function can also be used with NULL as argument to check whether a command processor exists.

Parameters

command
C string containing the system command to be executed.

Return Value

The value returned when the argument passed is not NULL, depends on the running environment specifications. In many systems, 0 is used to indicate that the command was successfully executed and other values to indicate some sort of error.
When the argument passed is NULL, the function returns a nonzero value if the command processor is available, and zero otherwise.

Portability

The behavior and return value are platform-dependent.

Example

123456789101112131415
/* system example : DIR */#include <stdio.h>#include <stdlib.h>int main (){  int i;  printf ("Checking if processor is available...");  if (system(NULL)) puts ("Ok");    else exit (1);  printf ("Executing command DIR...\n");  i=system ("dir");  printf ("The value returned was: %d.\n",i);  return 0;}

5.排序和查找<stdlib.h>


原创粉丝点击