我正在从事C++练习。它要求我打印一个双,但是我尝试了以下代码几次,但是没有用。如何在以下代码中将GPA打印为双份?
#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;
}
结果出来的
“学生:783-92-4716单位:100级分数:345 GPA:3”
但是我期望的是
“学生:783-92-4716单位:100级分数:345 GPA:3.45”
如何获得GPA中的整数而不是GPA中的整数?
最佳答案
您可以通过包含一个操纵器轻松地完成操作。该操纵器在头<iomanip>
中声明。并直接在std::cout
上设置精度,并使用std::fixed
格式说明符。
#include <iomanip> // std::setprecision
double gpa(){
int gpa = 100*gradepts/units;
std::cout << std::setprecision(3) << gpa/100.0 << '\n'; // you can set your precission to a value you plan to use
std::cout << std::fixed;
return gpa/100.0;
}
这应该使您的更正工作为:
#include <iostream>
#include <iomanip> // std::setprecision
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 = 100*gradepts/units;
std::cout << std::setprecision(3) << gpa/100.0 << '\n'; // you can set your precission to a value you plan to use
std::cout << std::fixed;
return gpa/100.0;
}
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;
}
我希望这能解决您的问题。
关于c++ - 如何在C++中打印 double ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48859063/