我是C++的新手,并努力弄清楚为什么我的代码完美运行但在运行后仍然返回一个荒谬的数字

0 c++

我想确定一个数字是偶数还是奇数.因为我想练习我对类的新知识,所以我编写了一个类并构建了一个函数来帮助我确定数字是奇数还是偶数.

在编译和测试我的代码之后,它运行得很完美.但是在打印出函数中嵌入的print语句之后,它也会输出很多数字.

为什么程序会返回该数字?

 #include <iostream>

    using namespace std;

    class numbers{

        public:
           int odev(int num)
           {
              if (num % 2 == 0){
                cout << num << " is an even number" << endl;
              }
              else{
                cout << num << " is an odd number" << endl;
              }

           }

            int greatest_number(int fnum, int snum, int tnum)
            {
                if (fnum > snum && fnum > tnum){
                    cout << fnum << " is greatest among these" << endl;
            }
                    else if (snum > fnum && snum > tnum){
                        cout << snum << "is greatest among these" << endl;
                    }
                else{
                    cout << tnum << " is the greatest among these" << endl;
                }
            }
    };
    int main()
    {
        numbers arit;
        float d;

        cout <<"Enter any number: \n> ";
        cin >> d;

        cout << arit.odev(d) << endl;

        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

这就是它所展示的.
这就是它所展示的.

R S*_*ahu 5

odev即使返回类型为,成员函数也不会返回任何内容int.因此,您的程序具有未定义的行为.

您可以通过添加return语句或将返回类型更改为void和替换来修复它

cout << arit.odev(d) << endl;
Run Code Online (Sandbox Code Playgroud)

arit.odev(d);
Run Code Online (Sandbox Code Playgroud)

成员函数greatest_number遇到同样的问题.


您可以通过调高警告级别在编译时检测此类错误.当我使用编译发布的代码时g++ -Wall,我收到以下消息.

socc.cc: In member function ‘int numbers::odev(int)’:
socc.cc:17:7: warning: no return statement in function returning non-void [-Wreturn-type]
       }
       ^
socc.cc: In member function ‘int numbers::greatest_number(int, int, int)’:
socc.cc:30:7: warning: no return statement in function returning non-void [-Wreturn-type]
       }
Run Code Online (Sandbox Code Playgroud)