C相關函數

1.字符串中經常使用的系統函數

說明:字符串(即字符數組)在程序開發中使用很是多,經常使用的函數須要掌握程序員

  • 獲得字符串的長度 size_t strlen(const char *str)編程

    • 計算字符串str的長度,直到空結束字符,但不包括空結束字符
  • 拷貝字符串 char *strcpy(char *dest,const char *src)數組

    • 把src所指向的字符串複製到dest
  • 鏈接字符串 char *strcat(char *dest,const char *src)函數

    • 把src所指向的字符串追加到dest所指向的字符串的結尾
#include <stdio.h>
#include <string.h>
//頭文件中聲明字符串相關的系統函數

void main(){
    char src[50] = "abc",dest[50];
    //定義兩個字符數組(字符串),大小爲50
    char *str = "abcdef";
    printf("str.len=%d",strlen(str));//統計字符串的大小
    
    //表示將「hello」拷貝到src
    //注意:拷貝字符串會將原來的內容覆蓋
    strcpy(src,"hello");
    printf("src=%s",src);
    
    strcpy(dest,"尚硅谷");
    
    //strcat是將src字符串的內容鏈接到dest,可是不會覆蓋dest原來的內容,而實鏈接
    strcat(dest,src);
    printf("最終的目標字符串:dest=%s",dest);
    getchar();
    
}

2 . 時間和日期相關函數

說明:在編程中,程序員會常用到日期相關的函數,好比:統計某段代碼花費的時間,頭文件是<time.h>code

  • 獲取當前時間 char *ctime(const time_t *timer)開發

    • 返回一個表示當地時間的字符串,當地時間是基於參數timer
  • 編寫一段代碼來統計函數test執行的時間字符串

    • double difftime(time_t time,time_t time2)
    • 返回time1和time2之間相差的秒數(time1-time2)
#include<stdio.h>

#include<time.h>//該頭文件中,聲明和日期和時間相關的函數
void test(){
    //運行test函數,看看花費多少時間
    int i=0;
    int sum=0;
    int j=0;
    for(i=0;i<777777777,i++){
        sum=0;
        for(j=0;j<10;j++){
            sum+=j;
        }
    }
}

int main(){
    time_t curtime;//time_h是一個結構體類型
    time(&curtime);//time()完成初始化
    //ctime返回一個表示當地時間的字符串,當地時間是基於參數timer
    printf("當前時間=%s",ctime(&curtime));
    getchar();
    return 0;
    
    //先獲得執行test前的時間
    
    time_t start_t,end_t;
    double diff_t;//存放時間差
    printf("程序啓動...");
    time(&start_t);//初始化獲得當前時間
    
    test();
    
    //再獲得test後的時間
    time(&end_t);//獲得當前時間
    diff_t=difftime(end_t,start_t);//時間差,按秒ent_t - start_t
    
    //而後獲得兩個時間差就是耗用的時間、
    printf("執行test()函數耗用了%.2f秒",diff_t);
    getchar();
    return 0;
}

3 . 數學相關函數

math.h 頭文件定義了各類數學函數和一個宏,在這個庫中全部可用的功能都帶有一個double類型的參數,且都返回double類型的結果get

  • double exp(double x) 返回e的x次冪的值
  • double log(double x) 返回x的天然對數(基數爲e的對數)
  • double pow(double x,double y) 返回x的y次冪
  • double sqrt (double x) 返回x的平方根
  • double fabs(double x) 返回x的絕對值
#include <stdio.h>
#include <math.h>

void main(){
    double d1=pow(2.0,3.0);
    double d2=sqrt(5.0);
    printf("d1=%.2f",d1);
    printf("d2=%.2f",d2);
    getchar();
}
相關文章
相關標籤/搜索