为什么我的程序在运行时输出"0",即使它不应该也输出?

Why is my program is outputting '0' when run, even though it is not supposed too?

本文关键字:输出 不应该 程序 我的 运行时 为什么      更新时间:2023-10-16

我对 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语句而不是使用函数直接输出,因此在这种情况下,第一种解决方案更好。

如果出现任何问题,请随时提出进一步的问题。