数字

117 阅读4分钟

数字

当我们使用数字时,通常我们使用原始数据类型,例如 int,short,long,float 和 double 等。数字数据类型,它们的可能值和取值范围在讨论 C++ 数据类型时已经解释了。

在 C++ 程序中定义数字

在之前的章节中,我们定义了多种数字类型。下面的例子定义了多种数字类型:

#include <iostream>
using namespace std;

int main() {
  // number definition:
  short  s;
  inti;
  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 << "inti :" << i << endl;
  cout << "long   l :" << l << endl;
  cout << "float  f :" << f << endl;
  cout << "double d :" << d << endl;

  return 0;
}

当上述代码被编译执行时,它将产生下面的结果:

short  s :10
inti :1000
long   l :1000000
float  f :230.47
double d :30949.4

C++ 中的数学运算

您除了可以创建各种各样的函数外,C++ 中还包括一些你可以使用的已经存在的函数。这些函数在标准的 C 和 C++ 库中都可以使用,被成为内置函数。这些函数都可以包含在您的程序中,然后使用。

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

要利用这些函数,你需要包括<cmath>这个数学头文件。

序号 函数和功能
1 double cos(double); 这个函数输入一个角度(作为一个双精度)并返回余弦值。
2 double sin(double); 这个函数输入一个角度(作为一个双精度)并返回正弦值。
3 double tan(double); 这个函数输入一个角度(作为一个双精度)并返回正切值。
4 double log(double); 这个函数输入一个数字并返回该数字的自然对数。
5 double pow(double,double); 第一个参数是你想要增长的数字,第二个参数是你想要将它增长的倍数。
6 double hypot(double,double); 如果你向该函数传递一个直角三角形的两个边的长度,它将返回你的直角三角形的斜边长度。
7 double sprt(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;
  inti = -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