《你必须知道的495个C语言问题》笔记--库函数

来源:互联网 发布:阿里云注销 编辑:程序博客网 时间:2024/05/01 09:47

怎样把数字转为字符串(与atoi相反)?有itoa函数吗?

用sprintf就可以了:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. sprintf(string, "%d", number);  
同理,也可以同sprintf把long型或浮点型转换成字符串(使用%ld或%f),也就是说,可以把sprintf看成是atol或者atof的

反函数。


怎样在日期上加n天?怎样取得两个日期的时间间隔?

第一个问题,mktime接受没有规范话的日期,所以可以用一个日期的struct tm结构,直接在tm_mday域上进行加减,然后

调用mktime进行规范化,同时也返回了time_t值。但是主要不要超过tm中成员域的最大表示范围。

实践如下:

在2014/5/16日上加20天。

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <time.h>  
  3.   
  4. int main(void)  
  5. {  
  6.         struct tm tm1;  
  7.         tm1.tm_year = 2014 - 1900;  
  8.         tm1.tm_mon = 5 - 1;  
  9.         tm1.tm_mday = 16;  
  10.         tm1.tm_hour = tm1.tm_min = tm1.tm_sec = 0;  
  11.         tm1.tm_isdst = 0;  
  12.   
  13.         tm1.tm_mday += 20;  
  14.         if (mktime(&tm1) == -1) {  
  15.   
  16.         } else {  
  17.                 printf("%d/%d/%d\n",tm1.tm_year+1900, tm1.tm_mon+1, tm1.tm_mday);  
  18.         }  
  19.         return 0;  
  20. }  
运行结果:

2014/6/5

第二个问题,可以使用mktime的返回值time_t,然后调用difftime获取他们的差值。

实践如下:

获取2014/5/16 到2014/6/5值

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <time.h>  
  3.   
  4. int main(void)  
  5. {  
  6.         struct tm tm1,tm2;  
  7.         tm1.tm_year = 2014 - 1900;  
  8.         tm1.tm_mon = 5 - 1;  
  9.         tm1.tm_mday = 16;  
  10.         tm1.tm_hour = tm1.tm_min = tm1.tm_sec = 0;  
  11.         tm1.tm_isdst = 0;  
  12.   
  13.         tm2.tm_year = 2014 - 1900;  
  14.         tm2.tm_mon = 6 - 1;  
  15.         tm2.tm_mday = 5;  
  16.         tm2.tm_hour = tm1.tm_min = tm1.tm_sec = 0;  
  17.         tm2.tm_isdst = 0;  
  18.   
  19.         time_t t1,t2;  
  20.         t1 = mktime(&tm1);  
  21.         t2 = mktime(&tm2);  
  22.   
  23.         long d = difftime(t2,t1)/86400;  
  24.         printf("%ld\n",d);  
  25.         return 0;  
  26. }  
运行结果:

20


如何生成随机数?

使用rand函数。从srand (seed)中指定的seed开始,返回一个[0, RAND_MAX]间的随机整数。RAND_MAX被定义在stdlib.h

中:

/* The largest number rand will return (same as INT_MAX).  */
#define RAND_MAX        2147483647

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3.   
  4. int main(void)  
  5. {  
  6.         printf("%d\n", rand());  
  7.         return 0;  
  8. }  
但是每次运行的结果都是相同的:

1804289383

为了避免每次产生的随机数序列相同,通常用srand((unsigned)time(0))或者srand((unsigned)time(NULL))来产生种子:

rand()在每次被调用的时候,它会查看:
1)如果用户在此之前调用过srand(seed),给seed指定了一个值,那么它会自动调用srand(seed)一次来初始化它的起始值。
2) 如果用户在此之前没有调用过srand(seed),它会自动调用srand(1)。

所以上面的程序每次执行结果都是相同的。下面添加srand调用:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3.   
  4. int main(void)  
  5. {  
  6.         srand((unsigned)time(NULL));  
  7.         printf("%d\n", rand());  
  8.         return 0;  
  9. }  
执行结果:

1307772800

2067487507

但是如果在同一时间运行(精确到秒),则还是会出现相同的现象。

0 0
原创粉丝点击