C++ 中的数字
通常,当我们使用数字时,我们使用原始数据类型,例如 int、short、long、float 和 double 等。数字数据类型、它们可能的值和数字范围已经在讨论 C++ 数据类型时进行了解释。
在 C++ 中定义数字
您已经在前面章节中给出的各种示例中定义了数字。这是另一个在 C++ 中定义各种类型数字的综合示例 -
#include <iostream>
using namespace std;
int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
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++ 中可用的一些有用的内置数学函数。
要使用这些函数,您需要包含数学头文件<cmath>。
| 先生编号 | 功能与目的 |
|---|---|
| 1 | 双余弦(双); 该函数接受一个角度(作为双精度值)并返回余弦值。 |
| 2 | 双罪(双); 该函数接受一个角度(作为双精度值)并返回正弦值。 |
| 3 | 双棕褐色(双); 该函数接受一个角度(作为双精度值)并返回正切值。 |
| 4 | 双对数(双); 该函数接受一个数字并返回该数字的自然对数。 |
| 5 | 双战俘(双,双); 第一个是您希望提高的数字,第二个是您希望提高的功率 |
| 6 | 双hypot(双,双); 如果您向此函数传递直角三角形两条边的长度,它将返回斜边的长度。 |
| 7 | 双开方(双); 您向该函数传递一个数字,它会给出平方根。 |
| 8 | int 绝对值(int); 此函数返回传递给它的整数的绝对值。 |
| 9 | 双晶圆厂(双); 此函数返回传递给它的任何十进制数的绝对值。 |
| 10 | 双层(双人); 查找小于或等于传递给它的参数的整数。 |
以下是一个简单的例子,展示了一些数学运算 -
#include <iostream>
#include <cmath>
using namespace std;
int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
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;
}
当上面的代码被编译并执行时,它会产生以下结果 -
sign(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;
// set the seed
srand( (unsigned)time( NULL ) );
/* generate 10 random numbers. */
for( i = 0; i < 10; i++ ) {
// generate actual random number
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