一般,當咱們須要用到數字時,咱們會使用原始的數據類型,如 int、short、long、float 和 double 等等。這些用於數字的數據類型,其可能的值和數值範圍,咱們已經在 C++ 數據類型一章中討論過。ios
咱們已經在以前章節的各類實例中定義過數字。下面是一個 C++ 中定義各類類型數字的綜合實例:函數
#include <iostream>
using namespace std;
int main ()
{
// 數字定義
short s;
int i;
long l;
float f;
double d;
// 數字賦值
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// 數字輸出
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;
}spa
當上面的代碼被編譯和執行時,它會產生下列結果:3d
在 C++ 中,除了能夠建立各類函數,還包含了各類有用的函數供您使用。這些函數寫在標準 C 和 C++ 庫中,叫作內置函數。您能夠在程序中引用這些函數。orm
C++ 內置了豐富的數學函數,可對各類數字進行運算。下表列出了 C++ 中一些有用的內置的數學函數。blog
爲了利用這些函數,您須要引用數學頭文件 <cmath>。md5
下面是一個關於數學運算的簡單實例:數學
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
// 數字定義
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// 數學運算
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;
}hash
當上面的代碼被編譯和執行時,它會產生下列結果:it
在許多狀況下,須要生成隨機數。關於隨機數生成器,有兩個相關的函數。一個是 rand(),該函數只返回一個僞隨機數。生成隨機數以前必須先調用 srand() 函數。
下面是一個關於生成隨機數的簡單實例。實例中使用了 time() 函數來獲取系統時間的秒數,經過調用 rand() 函數來生成隨機數:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main ()
{
int i,j;
// 設置種子
srand( (unsigned)time( NULL ) );
/* 生成 10 個隨機數 */
for( i = 0; i < 10; i++ )
{
// 生成實際的隨機數
j= rand();
cout <<"隨機數: " << j << endl;
}
return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果: