C++ 中的数字
通常,当我们处理 Numbers 时,会使用原始数据类型,例如 int、short、long、float 和 double 等。数字数据类型、它们可能的值和数字范围已在讨论 C++ Data Types 时解释过。
在 C++ 中定义数字
您已经在前几章给出的各种示例中定义了数字。这里是一个综合示例,用于在 C++ 中定义各种类型的数字 −
#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
C++ 中的数学运算
除了您可以创建的各种函数外,C++ 还包含一些有用的函数供您使用。这些函数可在标准 C 和 C++ 库中使用,被称为 内置 函数。这些是可以包含在您的程序中然后使用的函数。
C++ 拥有丰富的数学运算集,可对各种数字执行运算。下表列出了一些在 C++ 中可用的有用内置数学函数。
要使用这些函数,需要包含 math 头文件 <cmath>。
| 序号 | 函数 & 用途 |
|---|---|
| 1 | double cos(double); 该函数接受一个角度(double 类型)并返回余弦值。 |
| 2 | double sin(double); 该函数接受一个角度(double 类型)并返回正弦值。 |
| 3 | double tan(double); 该函数接受一个角度(double 类型)并返回正切值。 |
| 4 | double log(double); 该函数接受一个数字并返回该数字的自然对数。 |
| 5 | double pow(double, double); 第一个参数是要幂运算的数字,第二个参数是要幂的指数 |
| 6 | double hypot(double, double); 如果您向该函数传递直角三角形的两条边的长度,它将返回斜边的长度。 |
| 7 | double sqrt(double); 您向该函数传递一个数字,它将返回平方根。 |
| 8 | int abs(int); 该函数返回传递给它的整数的绝对值。 |
| 9 | double fabs(double); 该函数返回传递给它的任何十进制数的绝对值。 |
| 10 | double floor(double); 找出小于或等于传递给它的参数的整数。 |
以下是一个简单示例,展示了一些数学运算 −
#include <iostream>
#include <cmath>
using namespace std;
int main () {
// 数字定义:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// 数学运算;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
}
当上述代码编译并执行时,会产生以下结果 −
sin(d) :-0.634939 abs(i) :1000 floor(d) :200 sqrt(f) :15.1812 pow( d, 2 ) :40149.7
C++ 中的随机数
在许多情况下,你会希望生成一个随机数。实际上,有两个函数你需要了解用于随机数生成。第一个是 rand(),这个函数只会返回一个伪随机数。解决方法是首先调用 srand() 函数。
以下是一个简单的示例,用于生成几个随机数。这个示例利用 time() 函数获取系统时间的秒数,来为 rand() 函数提供随机种子 −
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main () {
int i,j;
// 设置种子
srand( (unsigned)time( NULL ) );
/* 生成 10 个随机数。 */
for( i = 0; i < 10; i++ ) {
// 生成实际的随机数
j = rand();
cout <<" Random Number : " << j << endl;
}
return 0;
}
当上面的代码被编译并执行时,它会产生以下结果 −
Random Number : 1748144778 Random Number : 630873888 Random Number : 2134540646 Random Number : 219404170 Random Number : 902129458 Random Number : 920445370 Random Number : 1319072661 Random Number : 257938873 Random Number : 1256201101 Random Number : 580322989