我几乎是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
andmark2
are integers and so is2
thus, it will provide you an integer.Try replacing
2
with2.0
to achieve floating point division.And as your
disp
function is not returning something you need not tocout
it. You can do this,在此表达式中:
you are doing integer division, since both the variables and the literal are
int
types. You could simply do:相反,要进行浮点除法。
To get
disp
to work, note that it doesn't return anything, so you need to simply call it like this:and not pass the result of this function to
cout
.Alternatively, instead of
disp
, you can overload theoperator<<
like this:然后像这样使用它: