如何显示一个类的值?

我几乎是C ++的新手。我开设了一个学生班。首先,当我返回标记的媒体时,它不是浮点值。例如:如果我输入5和10,它将返回7而不是7.5。

其次,当我想用​​函数disp()显示名称和媒体时,它不起作用。

有人可以帮忙吗?

谢谢

#include <iostream>
using namespace std;

class student{
    public:
        string name;
        int mark1, mark2;

        float calc_media(){ 
            float media = (mark1 + mark2)/2; 

            return media; 

        }
        void disp(){
            cout << "Student:" << name << endl;
            cout << "media:"<< calc_media() << endl;
        }

};



int main (){
    student peter;

    cout <<"name:" ;
    cin>>peter.name;
    cout <<"mark1:" ;
    cin>>peter.mark1;
    cout <<"mark2:" ;
    cin>>peter.mark2;
    cout <<"ALL:" << peter.disp();




    return 0;
}


编辑: 我也知道我可以做这样的事情:

我已经删除了该函数的功能,并且已经将该类写出了,但是它不起作用。

#include <iostream>
using namespace std;

class student{
    public:
        string name;
        int mark1, mark2;

        float calc_media(int, int);

        void disp(){
            cout << "Student:" << name << endl;
            cout << "Media:"<< calc_media(int, int) << endl;
        }


};

student::float calc_media(int x, int y){
    float media = (x + y)/2.0; 

    return media; 
}


int main (){
    student peter;

    cout <<"name:" ;
    cin>>peter.name;
    cout <<"mark1:" ;
    cin>>peter.mark1;
    cout <<"mark2:" ;
    cin>>peter.mark2;
    cout <<"media:" << peter.calc_media(peter.mark1, peter.mark2) << endl << endl;

    peter.disp();

    return 0;
}

评论
果粒、橙
果粒、橙

Here what you are doing is called integer division, both variables mark1 and mark2 are integers and so is 2 thus, it will provide you an integer.

float calc_media(){ 
            float media = (mark1 + mark2)/2; 

Try replacing 2 with 2.0 to achieve floating point division.

float media = (mark1 + mark2)/2.0; 

And as your disp function is not returning something you need not to cout it. You can do this,

cout <<"ALL:";
peter.disp();
点赞
评论
柠檬心
柠檬心

在此表达式中:

(mark1 + mark2) / 2;

you are doing integer division, since both the variables and the literal are int types. You could simply do:

(mark1 + mark2) / 2.0;

相反,要进行浮点除法。

To get disp to work, note that it doesn't return anything, so you need to simply call it like this:

peter.disp();

and not pass the result of this function to cout.

Alternatively, instead of disp, you can overload the operator<< like this:

std::ostream& operator<<(student const &s, std::ostream &out)
{
  out << "Student:" << name << endl;
  out << "media:"<< calc_media() << endl;
  return out;
}

然后像这样使用它:

cout << peter;
点赞
评论