我做了一個基於函數重載的程序,它由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
誰能幫助我關於 感謝
我建議使用模板方法 – Simon
問題標題並沒有真正提供有關問題的任何線索。這個問題在初學者中必須是相當普遍的,但我無法通過快速搜索找到一個問題。 – Walter