(C++) 为什么该程序在输出中给出“0”或 "nan"?

(C++) Why this program is giving the "0" or "nan" in the output?

我有这个简单的 C++ 程序,我必须在其中输入 5 个科目的分数并计算它的百分比。但我不知道为什么在输出中显示 "0" 并且如果我删除 input() 下的那些 return 0 语句和 percentage() 函数然后它在输出中显示 "nan"

Here is the code:

#include<iostream>
using namespace std;

class Marks
{
    float s1,s2,s3,s4,s5;
    float p;
public:
    float input();
    float percentage();
};

float Marks::input()
{
    cout<<endl<<"Enter the marks of your 5 subjects."<<endl;
    cin>>s1>>s2>>s3>>s4>>s5;
    cout<<"Subject 1="<<s1<<endl<<"Subject 2="<<s2<<endl<<"Subject 3="<<s3<<endl<<"Subject 4="<<s4<<endl<<"Subject 5="<<s5<<endl;
    //return 0;
}

float Marks::percentage()
{
    p=s1+s2+s3+s4+s5;
    p=p/5;
    cout<<p<<endl;
    //return 0;
}

int main()
{
    Marks student1;
    cout<<"Marks of student 1 are as follow:"<<endl<<student1.input()<<endl;
    cout<<"Student 1: Percentage = "<<student1.percentage()<<endl;
  return 0;
}

And this is the output:

您的函数承诺 return 一个 float,但他们没有。即undefined behaviour。一旦你的程序包含UBanywhere,它就变得毫无意义了。