为什么我的程序在运行时输出"0",即使它不应该也输出?
Why is my program is outputting '0' when run, even though it is not supposed too?
我对 c++ 很陌生,只是在玩 if 语句,所以我做了这个程序:
#include <iostream>
using namespace std;
int getMax(int num1, int num2){
if (num1>num2)
{
cout << num1 <<endl;
}else{
cout << num2 <<endl;
}
return EXIT_SUCCESS;
}
int main(){
cout<<getMax(7,13)<<endl;
return 0;
}
我的 getMax 函数需要两个参数,应该输出 2 个数字中较大的一个——在本例中为 13。但它不仅输出 13,还输出 0。为什么会这样?
但它不仅输出 13,还输出 0。为什么会这样?
因为在此声明中:
cout<<getMax(7,13)<<endl;
您发送到cout
getMax()
调用的结果,该结果是计算结果为 0 EXIT_SUCCESS
宏。
看起来您的getMax()
函数应该返回最大值而不是打印它:
int getMax(int num1, int num2)
{
return num1 > num2 ? num1 : num2;
}
但是您应该改用std::max()
,或者至少将函数重命名为 printMax()
它还输出 0。为什么会这样?
因为你告诉它:
cout << getMax(7,13) << endl;
这会将 getMax
的返回值打印到标准输出(并刷新(它。返回值为 EXIT_SUCCESS
,即零。如果您不想打印返回值,只需将该函数调用
getMax(7, 13);
或者更改其实现,以便返回更大的值,而不是打印出来(这就是函数名称所暗示的!
lubgr 和 Slava 已经解释了为什么程序输出 0,我只是想补充一点,做这样的事情是更好的编程风格:
#include <iostream>
using namespace std; //this is considered bad practice, it is better to use std::cout etc.
int getMax(int num1, int num2) {
if (num1 > num2){
return num1; //this makes the return 0 unnecessary
}
else if (num1 < num2) {
return num2; //this makes the return 0 unnecessary
}
else {
return num1; //case num1 == num2, it doesn't matter which num you return
}
int main () {
cout << getMax (7, 13) >> 'n';
return 0;
}
我建议不要使用不必要的返回语句(但通常不反对返回语句,它们比直接输出更好(,因为它们会导致非常随机的错误,很难捕获。或者,您可以使用不返回任何内容的void
函数,当仅使用该函数输出某些内容时,这被认为是常见做法:
#include <iostream>
void getMax(int num1, int num2) {
if (num1 > num2){
std::cout << num1 << 'n';
}
else if (num1 < num2) {
std::cout << num2 << 'n';
}
}
int main () {
getMax (7, 13);
return 0;
}
正如纪尧姆在评论中提到的,通常最好使用return
语句而不是使用函数直接输出,因此在这种情况下,第一种解决方案更好。
如果出现任何问题,请随时提出进一步的问题。
相关文章:
- 条件断点在不应该触发时触发
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么我不应该把所有东西都放在标题中?
- 找不到 QRegularExpression 行为的任何解释。它有效,但不应该
- 在清除 istream 之前,我不应该需要取消获取它吗?
- c++ 为什么我不应该从不同的线程解锁互斥锁
- 为什么Qt Creator的应用程序输出不能从spdlog记录器打印
- Windows 10命令提示符的输出不正确
- "typename"不应该只在模板函数或模板类中使用吗?
- 为什么数组到指针的输出不相关
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- 程序的输出不是来的,它是一个链表程序
- C++ - 为什么 unicode 输出不正确?
- 为不应该获得未定义行为的内容获取未定义的行为
- 存储和打印字符,但输出不是预期的
- 两种情况下的输出不应该相同吗?
- 我的叉子输出不正确
- 默认情况下,"std::shared_ptr"不应该使用"std::d efault_delete"吗?
- 为什么我的程序在运行时输出"0",即使它不应该也输出?
- 这些代码之间的区别在哪里?输出不应该是一样的吗?