数字
1.C++ 定义数字
flog只能输出小数点后三位
double只能输出小数点后一位
#include <iostream>
using namespace std;
int main ()
{
// 数字定义
short s;
int i;
long l;
float f;
double d;
// 数字赋值
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// 数字输出
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
运行结果
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
2.C++ 数学运算
数学头文件
具体参考《C语言程序设计(第三版)》P345
3.C++ 随机数
在许多情况下,需要生成随机数。关于随机数生成器,有两个相关的函数。一个是== rand(),该函数只返回一个伪随机数。生成随机数之前必须先调用 srand() 函数。
下面是一个关于生成随机数的简单实例。实例中使用了 time()== 函数来获取系统时间的秒数,通过调用 rand() 函数来生成随机数
无范围随机数rand()
有范围随机数rand()%(b-a+1)+a;范围【a,b】
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main ()
{
int i,j;
// 设置种子
srand( time( 0 ) );
/* 生成 10 个随机数 */
for( i = 0; i < 10; i++ )
{
// 生成实际的随机数
j= rand();
//j=rand()%100+1->[1,100]
cout <<"随机数: " << j << endl;
}
return 0;
}