如何在C ++中打印double

时间:2018-02-19 03:09:50

标签: c++ printing int double

我正在进行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中获得整数,而是如何获得双倍?

2 个答案:

答案 0 :(得分:2)

  

不是在GPA中获得整数,而是如何获得双倍?

使用时

    int gpa;
    gpa = double(gradepts)/units;

您正在截断double

如果您想保留至少两个小数点,可以使用:

double gpa(){
    int gpa = 100*gradepts/units;
    return gpa/100.0;
}

答案 1 :(得分:1)

您可以通过包含操纵器轻松完成。该操纵符在标题<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;
}

我希望这能解决你的问题。