2013-09-28 27 views
0

我在C++初學者,我碰到這個代碼就來了:我想我明白這一點。但是有沒有辦法讓這個更簡單?

#include <iostream> 
using namespace std; 

int main() 
{ 
    const long feet_per_yard = 3; 
    const long inches_per_foot = 12; 
    double yards = 0.0;      // Length as decimal yards 
    long yds = 0;        // Whole yards 
    long ft = 0;        // Whole feet 
    long ins = 0;        // Whole inches 
    cout << "Enter a length in yards as a decimal: "; 
    cin >> yards;        // Get the length as yards, feet and inches 
    yds = static_cast<long>(yards); 
    ft = static_cast<long>((yards - yds) * feet_per_yard); 
    ins = static_cast<long>(yards * feet_per_yard * inches_per_foot) % inches_per_foot; 
    cout<<endl<<yards<<" yards converts to "<< yds <<" yards "<< ft <<" feet "<<ins<<" inches."; 
    cout << endl; 
    return 0; 
} 

它的工作原理像您期望的,但我不喜歡所有的類型轉換業務。所以我改變了這本:

#include <iostream> 
using namespace std; 

int main() 
{ 
    long feet_per_yard = 3; 
    long inches_per_foot = 12; 
    long yards = 0.0; 

    long yds = 0;        // Whole yards 
    long ft = 0;        // Whole feet 
    long ins = 0;        // Whole inches 
    cout << "Enter a length in yards as a decimal: "; 
    cin >> yards;        // Get the length as yards, feet and inches 
    yds = yards; 
    ft = (yards - yds) * feet_per_yard; 
    ins = (yards * feet_per_yard * inches_per_foot) % inches_per_foot; 

    cout<<endl<<yards<<" yards converts to "<< yds <<" yards "<< ft <<" feet "<<ins<<" inches."; 
    cout << endl; 


    return 0; 
} 

這當然是因爲「長」沒有像「雙重」確實,十進制值權並不像預期的那樣?

但是,如果我將每個值更改爲'double'類型,那麼%不會與'double'一起使用。有沒有辦法讓這更容易?我聽說過fmod(),但CodeBlock IDE似乎無法識別fmod()?

此外,我嘗試'浮動',它似乎也不'浮動'工作。那麼,%工作的變量類型是什麼?我在哪裏可以找到這個參考?

+0

你說的「不承認'fmod'」是什麼意思?您需要同時包含正確的標題 - 「#include 」 - 並鏈接到數學庫 - 「-lm」。如果您已經完成了這兩項操作,您是否可以發佈您獲得的錯誤副本? – simonc

+5

@simonc in C++''應該用來代替 –

+0

好的,謝謝。此外,我嘗試'浮動',似乎%不''浮動'工作。那麼,%工作的變量類型是什麼?我在哪裏可以找到這個參考? – user2826094

回答

1

繼承就宣佈一切爲雙然後你就不需要投。

使用雙數更合理,因爲雙腳的數量是連續數量。

您也可以投在你的表達式,如:

int daysperweek = 7; 
double val = daysperweek * 52.0; // using 52.0 will use implicit conversion 
相關問題