【发布时间】:2018-11-20 21:01:34
【问题描述】:
我目前正在学习 C++。我在处理过载问题时遇到了麻烦。类中的函数应该接收数组和数组的大小作为输入并输出最小值。共有三个数组,包括 int、float 和 char。我的代码只能在 int 下工作。我不明白为什么我在下面附上了我的代码。谁能告诉我的错误? 我知道一定有比我更好的方法,我真的很想弄清楚为什么我的代码不适用于 float 和 char 大小写。任何帮助将不胜感激。
对于 int 情况,它可以正确输出最小值 2。但是对于 float 条件,它一直给我 0 而不是 float 列表中的数字。强>
主要功能
int main()
{
Compare c;
int arrayInt[5] = {65,43,2,898,678};
float arrayInF[4] = {4.5,4.9,4.3,6.5};
char arrayInC[6] = {'w','z','t','h','e','c'};
std::cout<<c.findSmaller(arrayInt, 5)<<" is the smallest of the input array\n";
std::cout<<c.findSmaller(arrayInF, 4)<<" is the smallest of the input array\n";
std::cout<<c.findSmaller(arrayInC, 6)<<" is the smallest of the input array\n";
return 0;
}
类
class Compare
{
public:
int findSmaller(int input1[],int input2);
float findSmaller(float input1[],int input2);
};
int Compare::findSmaller(int input1[], int input2)
{
int small;
for(int i=0;i<input2;i++)
{
if(input1[i]<input1[i+1])
{
small = input1[i];
input1[i+1] = small;
}
else
{
small = input1[i+1];
input1[i+1] = small;
}
}
return small;
}
float Compare::findSmaller(float input1[], int input2)
{
float small;
for(int i=0;i<input2;i++)
{
if(input1[i]<input1[i+1])
{
small = input1[i];
input1[i+1] = small;
}
else
{
small = input1[i+1];
input1[i+1] = small;
}
}
return small;
}
char Compare::findSmaller(char input1[], int input2)
{
char small;
for(int i=0;i<input2;i++)
{
if(input1[i]<input1[i+1])
{
small = input1[i];
input1[i+1] = small;
}
else
{
small = input1[i+1];
input1[i+1] = small;
}
}
return small;
}
【问题讨论】:
-
你能解释一下它是怎么不工作的吗?
-
对于 int 情况,它可以正确输出最小值 2。但是对于浮动条件,它一直给我 0 而不是浮动列表中的数字。
-
你的方法不适用于 int。你只是碰巧得到了正确的答案。
-
如此多的人在没有评论原因的情况下投了反对票。仅仅因为它是糟糕的代码并不意味着这是一个糟糕的问题。
标签: c++ class overloading