C語言是函數的語言。
一個C語言程序可以很大,但是通常是由多個函數組成的。從這個意義上說,函數往往就比較短小。一個程序需要由幾個函數來實現,這個取決于你對
C語言的掌握程度和領悟能力,沒有硬性規定,以方便編程、方便調試、方便升級為原則。一個程序分解成幾個函數,有利于快速調試程序,也有利于提高程序代碼的利用率。因為函數是可以多次被調用的,調用次數和調用場合沒有限制。除main函數以外,任何一個函數都可以調用另外一個函數。
而這篇文章,就是介紹C語言中的幾個函數,希望你們能對它們能有更深的理解。
對這方面感興趣或者想學習C/C 可以加群:558502932
1、時間函數
tm結構體詳細信息
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
時間函數的使用
問題:打印年月小時分秒格式的
步驟1:時間函數的使用
時間轉換函數:
char *asctime(const struct tm *t)
char *ctime(const time_t *t)
char tm* gmtime(const time_t *t)
char tm* localtime(const time_t *t)
頭文件:time.h
#include
#include
int main(int argc, const char * argv[])
{
time_t t = time(0); //獲取當前系統時間函數time()
struct tm* local = localtime(&t); //将系統時間轉換為本地時間
printf("%d年%d月%d日 %d:%d:%d\n", 1900 local->tm_year, local->tm_mon 1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec);
return 0;
//time()函數
//localtime()函數
//tm結構體成員的使用
}
2、随機函數
srand()和rand()配合使用
産生一個僞随機數序列,
Srand(time(0))
Srand(time(NULL)):僞随機數序列随着每次運行時間不一樣而變化
srand()和rand()配合使用
srand(unsigned seed)
#include
#include
#define MAX 10
int main()
{
int number[MAX] = { 0 };
int i;
srand((unsigned)time(NULL)); //播種子
for (i = 0; i < MAX; i )
{
number[i] = rand() % 100;
printf("%d ", number[i]);
}
printf("\n");
return 0;
}
3.math數學函數
int abs(int i):求整形的絕對值
fabs():轉換為float類型的絕對值
#include
#include
int main()
{
int a, b;
a = 1234;
b = -1234;
printf("%d 的絕對值是%lf", a, fabs(a));
printf("%d 的絕對值是%lf", b, fabs(b));
return 0;
}
double modf(double x,double *integer)
返回值是:小數成分(小數點後的部分),并設置整數的整數部分
#include
#include
int main()
{
double x,fractpart,intpart;
x = 8.123456;
fractpart = modf(x, &intpart);
printf("整數部分=%lf", intpart);
printf("小數部分=%lf",fractpart);
return 0;
}
double sqrt(double x)
返回的是x的平方根
#include
#include
int main()
{
printf("%lf 的平方根是%lf\n", 4.0, sqrt(4.0));
printf("%lf 的平方根是%lf\n", 5.0, sqrt(5.0));
return 0;
}
double fmod(double x,double y)
返回值x除以y的餘數 實數型
x%y:對付整形
#include
#include
int main()
{
float a,b;
int c;
a = 9.2;
b = 3.7;
c = 2;
printf("%f/%d=%lf\n", a, c, fmod(a, c));
printf("%f/%f=%lf\n", a, b, fmod(a, b));
return 0;
}
以上,就是我所介紹的幾個函數,希望能對你們正在學習C語言的同學有些幫助。
對着方面感興趣或者想學習C/C 可以加群:558502932
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!