C++ 中的数字
通常,当我们使用 Numbers 时,我们使用原始数据类型,例如 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++ 中可用的一些有用的内置数学函数。
要使用这些函数,您需要包含数学头文件
| Sr.No | 功能和用途 |
|---|---|
| 1 | 双cos(双); 这个函数接受一个角度(作为一个双精度)并返回余弦。 |
| 2 | 双罪(双); 这个函数接受一个角度(作为一个双精度)并返回正弦值。 |
| 3 | 双晒(双); 这个函数接受一个角度(作为一个双精度)并返回切线。 |
| 4 | 双对数(双); 此函数接受一个数字并返回该数字的自然对数。 |
| 5 | 双pow(双,双); 第一个是你想提高的数字,第二个是你想提高的力量t |
| 6 | 双重假设(双重,双重); 如果你给这个函数传递一个直角三角形两条边的长度,它会返回斜边的长度。 |
| 7 | 双平方(双); 你给这个函数传递一个数字,它就会给你平方根。 |
| 8 | int abs(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
C语言