2017-05-27 35 views
0

我做了一個基於函數重載的程序,它由2個函數int cube(int)和float cube(float)組成。我的主函數分別讀取int x和float y的值。現在,當我運行程序時,我將一個浮點值替換爲整數va; ue並且當我在變量「x」中放置2.5(十進制值)而不是整數值時,編譯器不會問我y的值,x(int)自動爲2,y(float)爲0.5,並返回0.5的立方體。爲什麼這是發生。爲什麼0.5會自動存儲在y中而不是詢問輸入?基於函數重載的程序

我的計劃是這樣的 -

#include<iostream> 
using namespace std; 
int main() 
{ 
    int x; 
    float y; 
    int cube(int); 
    float cube(float); 
    cout<<"Enter a number to find its cube"<<endl; 
    cin>>x; 
    cout<<"The cube of the number "<<x<<" is "<<cube(x)<<endl; 

    cout<<"Enter a number to find its cube"<<endl; 
    cin>>y; 
    cout<<"The cube of the number "<<y<<" is "<<cube(y)<<endl; 
    return 0; 
} 
int cube (int num) 
{ 
    return num*num*num; 
} 

float cube (float num) 
{ 
    return num*num*num; 
} 

輸出是 -

 
Enter a number to find its cube 
2.5 
The cube of number 2 is 8 
Enter the number to find its cube 
The cube of number 0.5 is 0.125 

誰能幫助我關於 感謝

+0

我建議使用模板方法 – Simon

+0

問題標題並沒有真正提供有關問題的任何線索。這個問題在初學者中必須是相當普遍的,但我無法通過快速搜索找到一個問題。 – Walter

回答

1

您嘗試讀取int值,但給一個浮點值作爲輸入。這意味着程序將讀取整數部分,只要看到與整數值模式不匹配的東西(在您的案例中爲'.'),就停止讀取,並將其保留在輸入緩衝區中以用於下一個輸入操作。

如果要讀取整行並放棄未分析的輸入,請在每次輸入後使用std::istream::ignore。或者使用std::getline將整行讀入字符串,並使用std::istringstream「解析」輸入。

0

這很簡單:

cout<<"Enter a number to find its cube"<<endl; 

你進入2.5

cin>>x; 

這種讀取2(套x=2)和停止,因爲.5不能是int的一部分。

cout<<"The cube of the number "<<x<<" is "<<cube(x)<<endl; 

cout<<"Enter a number to find its cube"<<endl; 
cin>>y; 

.5仍然在輸入流中,所以被讀出到設定y=0.5。無需輸入另一個號碼,因此程序不會停止等待輸入。