C语言的一些东西

来源:互联网 发布:mac os qq 英文 编辑:程序博客网 时间:2024/05/17 02:35

1:C语言中的ceil(),floor(),round():


ceil()

Prototype: double ceil(double x);
Header File: math.h (C) or cmath (C++)
Explanation: Use this to round a number up. It returns the smallest integergreater than or equal to x.
ANSI: C and C++

#include <cmath>#include <iostream>int main(){  cout<<ceil(2.0/4.0);  double x=.4;  cout<<ceil(x);} 

floor()

Prototype: double floor(double Value);
Header File: cmath
Explanation: Returns the largest interger value smaller than or equal to Value. (Rounds down)

#include <cmath>#include <iostream>using namespace std;int main(){  cout<<"5.9 rounded down: "<<floor(5.9);}

round()

double round(double value)

The round functions return the integral value nearest to x rounding half-way cases away from zero, regardless of the current rounding direction.


rand()与srand()


rand()

Prototype: int rand();
Header File: stdlib.h (C) or cstdlib (C++)

Explanation: rand returns a value between(inclusive) 0 and and RAND_MAX (defined by the compiler, often 32767). To get a more mangeale number, simply use the % operator, which returns the remainder of division.

srand()

use the spacified "seed" to act as the seed, then the rand can generate the numbers under this condition


在一些产品的源代码中,经常会发现有这样的语句,

srand(unsigned(time(NULL)));

为什么要这样做呢,其实很简单。

1.  time()函数表示返回1970-1-1 00:00:00 到当前时间的秒数,而time(NULL)表示获取一个时间,准确的说,获取一个指针的地址。

2.  srand()函数是产生随机数种子的。在产生随机数 rand()被调用的时候,他会查看:如果用户之前调用过 srand(seed)的话,他会重新调用一遍 srand(seed)以产生随机数种子;如果发现没有调用过 srand(seed)的话,会自动调用 srand(1)一次。所以,如果希望rand()每次调用产生的值都不一样,就需要每次调用srand(seed)一次,而且seed不能相同。

综合上述两点,那就很明了了。

srand(unsigned(time(NULL)))表示产生随机数种子以保证rand()调用的时候不会出现重复的随机值。

srand()、time(NULL)用法解析



原创粉丝点击