与函数中的返回值不同的数据类型

Different data types than return value in function?

本文关键字:数据类型 返回值 函数      更新时间:2023-10-16

好吧,我对我为学校制作的一个程序有点困惑。程序执行了,我得到了我想要的结果,但我只是觉得有些事情可能会更好。在我的findLowest()函数中,它有一个int返回。我在参数中传递给它的数据类型是double。一个具有一个返回类型的函数可以有不同的数据类型参数吗?或者我可以说,有没有一种更整洁的方法可以做到这一点,也许是选角?我不会有问题,但发现calcAverage()调用的最低需求让我很困惑,因为如果我更改数据成员,那么显然不会向每个函数传递正确的数据。这是该程序的代码片段,感谢您提前提出的任何想法,如果需要,它可以一直保持原样,它很有效。

//function averages input test scores
void calcAverage(double score1, double score2, double score3, double score4, double score5)
{   
    //call to findLowest() function to decide which score to omit
        double lowest = findLowest(score1, score2, score3, score4, score5); 
        double average = ((score1 + score2 + score3 + score4 + score5) - lowest) / 4;
        cout << "Average is: " << average << endl;
}
//determines which input score is lowest 
int findLowest(double score1, double score2, double score3, double score4, double score5)
{
    double low = score1;    
    if(score2 < low)
        low = score2;
    if(score3 < low)
            low = score3;
    if(score4 < low)
        low = score4;
    if(score5 < low)
        low = score5;
    cout << "Lowest score is: " << low << endl;

return low;
}

为什么不将findLowest的返回类型更改为double?

findLowest函数的主体中,您定义了double low,但将其返回为int,以便再次将其分配给double

将此返回值的类型从int更改为double,一切都会好起来。

"具有一个返回类型的函数可以有不同的数据类型参数吗?"
当然可以。返回值的类型不一定与参数的类型相关。

"问题在书中,书中说明了使用函数int findLowest的问题"
也许这本书的作者想让你做这样的事情:

#include <limits>
#include <vector>
...
int findLowest(vector<double>& v)
{
    int lowest = -1;
    double lowestValue = numeric_limits<double>::max();
    for (int i = 0; i < v.size(); ++i)
    {
        if (v[i] < lowestValue)
        {
            lowestValue = v[i];
            lowest = i;
        }
    }
    cout << "Lowest score is: " << lowestValue << " at index: " << lowest << endl;
    return lowest;
}
...
    // in calcAverage:
    vector<double> args;
    args.resize(5);
    args[0] = score1; args[1] = score2; args[2] = score3; args[3] = score4; args[4] = score5;
    int lowest = findLowest(args);
    args[lowest] = 0;
    double average = (args[0] + args[1] + args[2] + args[3] + args[4]) / 4;

当然可以。可以传入foo类型并返回bar类型。

然而,在你的例子中,你需要意识到一件事。将double的值分配给int类型时,会截断它们。所以你失去了精确性。如果你把0.254传进来,你可能会把0传出去。这可能不是被调用者所期望的。

我会更改findLowest,使其返回double,最好尽可能坚持正确的类型。

根据需求,一个更好的解决方案可能是返回一个int,表示五个数字中的哪一个更低。因此,如果您调用findLowest(2.3, 4, 0, 9, 6),它将返回2。findLowest(1, 2, 3, 4, 5) = 0