close

//---------------------------------------------------------------------------
#include <iostream>
/*
 * 這個程式可進行 0 到 100 之間攝氏和華氏溫度的轉換
 *
 * 條件:
 *    這個程式僅能處理整數,計算的結果可能不是十分精確
 */
//---------------------------------------------------------------------------
int celsius;     //要處理的攝氏溫度

int main(int argc, char* argv[])
{
        for (celsius = 0; celsius <= 100; ++celsius);
          std::cout << "celsius: " << celsius <<
                   " Fahrenheit: " << ((celsius * 9) / 5 + 32) << '\n';

        std::system("pause");
        return 0;
}
//---------------------------------------------------------------------------

執行時,這個程式會輸出:
    Celsius: 101    Fahrenheit: 213
就沒有其它的東西了,為什麼?

Answer: 問題是出在 for 敘述後的分號(;)。 for 主體是在右括號及分號之間,之間沒
有任何敘述,雖然 std::cout 敘述有縮排,但仍非 for 敘述的一部份。這個內縮格式
很容易誤導你,C++ 編譯器並不認得縮排。這個程式什麼都不做,直到運算式 
celsius <= 100 變成 false ( celsius == 101 )。接著才執行 std::cout。

題目來源:C++風格與藝術 第二版 Steve Oualline 著 黃吉霈 編譯

arrow
arrow
    全站熱搜

    jumbowind 發表在 痞客邦 留言(0) 人氣()