C++新人求助

来源:百度知道 编辑:UC知道 时间:2024/05/15 07:05:17
编写一个程序通过重载求2个数中较小的数,分别求2个实数和2个整数中的较小数。
请问主函数中怎么定义变量?int or

float?

int min(int a,int b)
{
return (a>b? a:b);
}
float min(float a,float b)
{
return (a>b? a:b);
}
这样就是重载了,调用时如果min(2,3),就是第一个函数,如果min(2.0,3.0)就是第二个函数

同意1楼的
主函数中int 和 float变量都要定义,因为你要分别求实数和整数中的最小值,程序大致如下:
#include <iostream.h>

int min(int a,int b)
{
return (a<b? a:b);
}
float min(float a,float b)
{
return (a<b? a:b);
}

void main()
{
int a,b;
float m,n;
cout<<"输入两个整数:";
cin>>a>>b;
cout<<"输入两个实数:";
cin>>m>>n;
cout<<"整数中较小的数:"<<min(a,b)<<endl;
cout<<"实数中较小的数:"<<min(m,n)<<endl;
}

不明白为什么楼上的都喜欢把返回值定为float

使用模板更加简单,不必重载。程序如下所示:
#include <iostream>
using namespace std;

template <class T>
T min(T a,T b)
{
return (a<b?a:b);