目录

C++ Numbers

通常,当我们使用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 ++库中可用,并称为built-in函数。 这些功能可以包含在您的程序中然后使用。

C ++有一组丰富的数学运算,可以在各种数字上执行。 下表列出了C ++中可用的一些有用的内置数学函数。

要使用这些函数,您需要包含数学头文件《cmath》

Sr.No 功能与目的
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 () {
   // 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++ Functions
C++ Arrays.下一篇>
↑回到顶部↑
WIKI教程 @2018