C语言的一些东西

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)用法解析



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值