通常,當我們需要用到數(shù)字時,我們會使用原始的數(shù)據(jù)類型,如 int、short、long、float 和 double 等等。這些用于數(shù)字的數(shù)據(jù)類型,其可能的值和數(shù)值范圍,我們已經(jīng)在 C++ 數(shù)據(jù)類型一章中討論過。
我們已經(jīng)在之前章節(jié)的各種示例中定義過數(shù)字。下面是一個 C++ 中定義各種類型數(shù)字的綜合示例:
#include <iostream>
using namespace std;
int main ()
{
// 數(shù)字定義
short s;
int i;
long l;
float f;
double d;
// 數(shù)字賦值
s = 25;
i = 3000;
l = 5000000;
f = 530.57;
d = 50348.574;
// 數(shù)字輸出
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;
}當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
short s :25 int i :3000 long l :5000000 float f :530.57 double d :50348.6
在 C++ 中,除了可以創(chuàng)建各種函數(shù),還包含了各種有用的函數(shù)供您使用。這些函數(shù)寫在標準 C 和 C++ 庫中,叫做內(nèi)置函數(shù)。您可以在程序中引用這些函數(shù)。
C++ 內(nèi)置了豐富的數(shù)學(xué)函數(shù),可對各種數(shù)字進行運算。下表列出了 C++ 中一些有用的內(nèi)置的數(shù)學(xué)函數(shù)。
為了利用這些函數(shù),您需要引用數(shù)學(xué)頭文件 <cmath>。
| 序號 | 函數(shù) & 描述 |
|---|---|
| 1 | double cos(double); 該函數(shù)返回弧度角(double 型)的余弦。 |
| 2 | double sin(double); 該函數(shù)返回弧度角(double 型)的正弦。 |
| 3 | double tan(double); 該函數(shù)返回弧度角(double 型)的正切。 |
| 4 | double log(double); 該函數(shù)返回參數(shù)的自然對數(shù)。 |
| 5 | double pow(double, double); 假設(shè)第一個參數(shù)為 x,第二個參數(shù)為 y,則該函數(shù)返回 x 的 y 次方。 |
| 6 | double hypot(double, double); 該函數(shù)返回兩個參數(shù)的平方總和的平方根,也就是說,參數(shù)為一個直角三角形的兩個直角邊,函數(shù)會返回斜邊的長度。 |
| 7 | double sqrt(double); 該函數(shù)返回參數(shù)的平方根。 |
| 8 | int abs(int); 該函數(shù)返回整數(shù)的絕對值。 |
| 9 | double fabs(double); 該函數(shù)返回任意一個浮點數(shù)的絕對值。 |
| 10 | double floor(double); 該函數(shù)返回一個小于或等于傳入?yún)?shù)的最大整數(shù)。 |
下面是一個關(guān)于數(shù)學(xué)運算的簡單示例:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
// 數(shù)字定義
short s = 20;
int i = -2000;
long l = 200000;
float f = 280.45;
double d = 300.456;
// 數(shù)學(xué)運算
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;
}當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
sin(d) :-0.907332 abs(i) :2000 floor(d) :300 sqrt(f) :16.7466 pow( d, 2) :90273.8
在許多情況下,需要生成隨機數(shù)。關(guān)于隨機數(shù)生成器,有兩個相關(guān)的函數(shù)。一個是 rand(),該函數(shù)只返回一個偽隨機數(shù)。生成隨機數(shù)之前必須先調(diào)用 srand() 函數(shù)。
下面是一個關(guān)于生成隨機數(shù)的簡單示例。示例中使用了 time() 函數(shù)來獲取系統(tǒng)時間的秒數(shù),通過調(diào)用 rand() 函數(shù)來生成隨機數(shù):
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main ()
{
int i,j;
// 設(shè)置種子
srand( (unsigned)time( NULL ) );
/* 生成 8 個隨機數(shù) */
for( i = 0; i < 8; i++ )
{
// 生成實際的隨機數(shù)
j= rand();
cout <<"隨機數(shù): " << j << endl;
}
return 0;
}當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
隨機數(shù): 21763 隨機數(shù): 15941 隨機數(shù): 846 隨機數(shù): 16376 隨機數(shù): 31767 隨機數(shù): 28949 隨機數(shù): 22265 隨機數(shù): 21475