2010-07-01 53 views
2

我是介紹性C++課程的學生。對於我們過去的任務之一,我們必須創建一個簡單的程序來添加分數。每個新實驗室只是應用了學習製作相同計劃的新技能。現在我需要使用類定義中的對象來創建一個對象。初始化值時的C++用戶輸入

經過一個倍增例子的工具,我的教授給了我們,我終於得到了正確添加分數的代碼。

#include <iostream> 
using namespace std; 

class Fraction 
{ 
private: 
    float numer; 
    float denom; 

public: 
    void Init(float n, float d); 
    void Multi(Fraction *, Fraction *); 
    void Print(); 
    Fraction() 
    { 
    numer = 0.0; 
    denom = 0.0; 
    } 
    void setNumer(float n) { numer = n; } 
    void setDenom(float d) { denom = d; } 
    float getNumer() { return numer; } 
    float getDenom() { return denom; } 
}; 

main() 
{ 
    Fraction x; 
    Fraction y; 
    Fraction f; 

    x.Init(1.0, 4.0); 
    y.Init(3.0, 4.0); 
    f.Init(0.0, 0.0); 

    f.Multi(&x, &y); 

    x.Print(); 
    y.Print(); 
    f.Print(); 
} 

void Fraction::Init(float n, float d) 
{ 
    numer = n; 
    denom = d; 
} 
void Fraction::Multi(Fraction *x, Fraction *y) 
{ 
    numer = (x->numer*y->denom) + (x->denom*y->numer); 
    denom = (x->denom*y->denom); 
} 
void Fraction::Print() 
{ 
    cout << "Fraction:" << endl; 
    cout << " Numerator: " << numer << endl; 
    cout << " Denominator: " << denom << endl; 
} 

Stackoverflow切斷我的代碼。 :/(不太清楚爲什麼,我對這個網站有點新鮮)

不管怎麼說,我真正想做的就是設置這個程序,這樣可以讓用戶輸入什麼x和y分數是。在我以前的任務中,我只使用了cin和cout命令,但現在不知道該怎麼做。一旦我知道了,我知道我可以使它適當地減少分數並正確顯示,但我不知道如何使它得到輸入。

有沒有人有任何建議? (或更好,如果你可以指導我到一個網站有更多的信息,如cplusplus.com我會很感激!)

回答

4

重命名您的Multi方法Add將避免很多潛在的混淆,並強烈建議。

至於輸入,有什麼問題(例如)std::cin >> numer >> denomnumerdenom聲明爲整數)?那麼當然你可以將它們傳遞給Init方法等。 (你可能還想在閱讀用戶輸入前自然地在std::cout上做提示)。

+0

首先,我想感謝您的快速反應。 發佈後的幾分鐘內,然後檢查,我嘗試了cin和cout命令,他們工作正常。 XD 我之前遇到了很多麻煩。 我也改變了添加。 非常感謝。 – AdamY 2010-07-01 04:28:26

+0

@AdamY,不客氣! – 2010-07-01 05:14:44

1

您有幾種選擇,從cin和init閱讀:

float n, d; 
cout << "Enter numerator: " << endl; 
cin >> n; 
cout << "Enter denominator: " << endl; 
cin >> d; 

x.Init(n, d); 

另外,棘手的選擇是允許的分子和分母成員直接訪問(這不會影響您Init功能工作):

class Fraction { 
public: 
    // other stuff ... 
    float &numerator() { return numer; } 
    float &denominator() { return denom; } 
    /// other stuff ... 
} 

cout << "Enter numerator: " << endl; 
cin >> x.numerator(); 
cout << "Enter denominator: " << endl; 
cin >> x.denominator();