我正在做一个 C++ 练习。它需要我打印一个 double,但我已经尝试了几次以下代码,但没有用。如何在以下代码中将 GPA 打印为 double ?
#include <iostream>
#include <string>
using namespace std;
class gradeRecord{
private:
string studentID;
int units,gradepts;
public:
gradeRecord(string stuID, int unts, int gpts){
studentID = stuID;
units = unts;
gradepts = gpts;
}
double gpa(){
int gpa;
gpa = double(gradepts)/units;
return gpa;
}
void updateGradeInfo(int unts,int gpts){
units = unts;
gradepts = gpts;
}
void writeGradeInfo(){
cout << "Student:" << studentID << "\t"
<< "Unit:" << units << "\t"
<< "GradePts:" << gradepts << "\t"
<< "GPA:" << gpa();
}
};
int main(){
gradeRecord studObj("783-29-4716", 100, 345);
studObj.writeGradeInfo();
return 0;
}
它的结果是 "Student:783-92-4716 Units:100 GradePts:345 GPA:3"
但我期望的是 "Student:783-92-4716 Units:100 GradePts:345 GPA:3.45"
除了在 GPA 中获得整数,我怎样才能获得双倍?
最佳答案
Instead of getting a integer in the GPA, how can I get a double?
当你使用
int gpa;
gpa = double(gradepts)/units;
您正在截断 double
。
如果你想保留至少两位小数,你可以使用:
double gpa(){
int gpa = 100*gradepts/units;
return gpa/100.0;
}
关于c++ - 如何在 C++ 中打印 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859063/