c++ - C++ 函数的返回值
问题描述
我遇到了一个问题,在解决过程中我得到了以下功能:
bool interesting(int n){
for(int i = 1; i <= n; i++){
if(sum(n+1, 0) < sum(n, 0)
return true;
}
}
也就是说,给定一个数字 n 来验证下一个数字的总和(n+1,0)是否小于前一个数字。但是我想知道该函数是返回真还是假,因为我有多个 i 要循环。
解决方案
int sum(int n, int m) { return -1; }
bool interesting(int n){
for(int i = 1; i <= n; i++){
if(sum(n+1, 0) < sum(n, 0))
return true;
}
// miss return here
}
int main() {}
这可能无法编译。即使它编译它也会产生一个未定义的行为。对于返回布尔值的函数,函数中的所有路径方式都应返回一个值。
警告:非 void 函数不会在所有控制路径中返回值
此外,一旦满足该条件,此函数将以 true 退出。我认为这是你需要的:
int sum(int n, int m) { return -1; }
bool interesting(int n){
bool result = true;
for(int i = 1; i <= n; i++){
if(!(sum(n+1, 0) < sum(n, 0)))
result = false;
}
return result;
}
编辑:我错误地认为您的代码不会编译。碰巧在某些编译器上它确实编译但发出警告
推荐阅读
- .net - Kinect SDK 1.8 只需安装语音识别语言
- javascript - 得到(node.js 库)无法在 FormData 中上传双工流
- python - 用户调用的“Create_stack”函数
- flutter - Flutter Listen 的 ChangeNotifier 类,它是 ChangeNotifier 的一个属性
- docker - 写入 docker bind mount 的文件在 jenkins 主机上不可见
- javascript - 反应原生汉字字符识别
- javascript - 如何通过单击将图像下载到客户端存储?
- php - Symfony 5 测试用例
- arrays - How can I read in characters with getchar() without the newline?
- object - 如何使两个对象之间的碰撞结合起来创建一个新对象?另外,我怎样才能将新对象发送到一个小时后被调用?