介紹

浮點數:3.1415926,0.8,7E5,2.52e+8

float(32位) double(64位) long double(至少跟double一樣)

區別:精度不一樣

#include <iostream>
#include <climits>
    
using namespace std;

int main() {
    cout << "float is " << sizeof(float) << " bytes." << endl;
    cout << "double is " << sizeof(double) << " bytes." << endl;
    cout << "long double is " << sizeof(long double) << " bytes." << endl;

    return 0; 
}

運行結果

xaye@orange:~/code/dev/4$ ./a.out 
float is 4 bytes.
double is 8 bytes.
long double is 16 bytes.

示例2:

#include <iostream>
#include <climits>
    
using namespace std;

int main() {

    // 用來設置輸出的格式
    cout.setf(ios_base::fixed,ios_base::floatfield);
    
    float tub = 10.0 / 3.0;
    double mint = 10.0 / 3.0;
    const float million = 1.0e6;

    cout << "tub = " << tub << ", a million tubs = " << million * tub << endl;
    cout << "and ten million tubs = " << 10 * million * tub << endl;

    cout << "mint = " << mint << ", a million tubs = " << million * mint << endl;
    cout << "and ten million mints = " << 10 * million * mint << endl;
    return 0; 
}

運行結果

xaye@orange:~/code/dev/4$ ./a.out 
tub = 3.333333, a million tubs = 3333333.250000
and ten million tubs = 33333332.000000
mint = 3.333333, a million tubs = 3333333.333333
and ten million mints = 33333333.333333

為什麼會這樣?

瞭解計算機是怎樣存儲數據的,IEEE-754 格式,32 位:1 位的符號位,8 位的指數位,底數位 23 位。


運算符

C++ 運算符:+ - * / %

#include <iostream>
#include <climits>
    
using namespace std;

int main() {

    float hats,heads;

    cout << "Enter a number: ";
    cin >> hats;
    cout << "Enter another number: ";
    cin >> heads;

    cout << "hats = " << hats << ", heads = " << heads << endl;
    cout << "hats + heads = " << hats + heads << endl;
    cout << "hats - heads = " << hats - heads << endl;
    cout << "hats * heads = " << hats * heads << endl;
    cout << "hats / heads = " << hats / heads << endl;

    // 算數優先級:都會
    // 3 + 4 * 5 ? 35 or 23

    cout << "Integer division: 9 / 5 = " << 9 / 5 << endl;
    cout << "Float-point division: 9.0 / 5.0 = " << 9.0 / 5.0 << endl;
    cout << "Mixed division: 9.0 / 5 = " << 9.0f / 5 << endl;
    

    return 0; 
}

運行結果

xaye@orange:~/code/dev/4$ ./a.out 
Enter a number: 5
Enter another number: 8
hats = 5, heads = 8
hats + heads = 13
hats - heads = -3
hats * heads = 40
hats / heads = 0.625
Integer division: 9 / 5 = 1
Float-point division: 9.0 / 5.0 = 1.8
Mixed division: 9.0 / 5 = 1.8