C++浮點類型表示具有小數部分的數字。
它們提供了更大的價值范圍。
C++有兩種寫入浮點數的方式。
第一個是使用標準的小數點符號:
12.34 // floating-point 987654.12 // floating-point 0.12345 // floating-point 8.0 // still floating-point
第二種方法稱為E符號,它看起來像這樣:3.45E6。
這意味著值3.45乘以1,000,000。
E6表示10到6的冪,即1后跟6個零。
因此3.45E6是3,450,000。
6稱為指數,3.45稱為尾數。
這里有更多的例子:
1.12e+8 // can use E or e, + is optional 1.12E-4 // exponent can be negative 7E5 // same as 7.0E+05 -12.12e13 // can have + or - sign in front
下面的代碼檢查float和double類型。
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point
float tub = 10.0 / 3.0; // good to about 6 places
double mint = 10.0 / 3.0; // good to about 15 places
const float million = 1.0e6;
cout << "tub = " << tub;
cout << ", a million tubs = " << million * tub;
cout << 10 * million * tub << endl;
cout << "mint = " << mint << " and a million mints = ";
cout << million * mint << endl;
return 0;
}
上面的代碼生成以下結果。
默認情況下,8.24和2.4E8的浮點常量是double類型。
如果創(chuàng)建一個常量為float類型,則使用f或F后綴。
對于long double類型,您可以使用l或L后綴。
以下是一些示例:
1.234f // a float constant 2.45E20F // a float constant 2.345324E28 // a double constant 2.2L // a long double constant
更多建議: