与函数中的返回值不同的数据类型
Different data types than return value in function?
好吧,我对我为学校制作的一个程序有点困惑。程序执行了,我得到了我想要的结果,但我只是觉得有些事情可能会更好。在我的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
等
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- H5Tget_member_type() 返回复合 HDF5 数据类型的奇怪值
- C++:将值赋值给原始数据类型(例如布尔值)是原子操作吗?
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 函数的返回值类型是别名 ***或 *** 布尔值
- 具有临时对象的 Fundamenta 数据类型赋值运算符
- 如何将预定义数据类型的值存储到数组中并输出它
- 从保存变量数据类型的数据结构中检索值,而不指定返回类型
- std::map使用不同的数据类型进行值
- C 策略设计具有可变类型返回值
- 使用函数操作结构数据类型的值
- 如何以不同的数据类型作为值实现地图
- 当我们给char数据类型赋值为负值时,它为什么表现得像int数据类型
- cpp函数来检索各种数据类型的值
- 多态性不适用于相同数据类型(Base和Inherited类)的函数返回值
- 引用数据类型的 & 符号是否返回引用本身的地址或它所引用的值
- 如何使用 cppunit 断言宏来检查返回数据类型的预处理器值
- C++模板:按类型返回值
- 与函数中的返回值不同的数据类型