c++ - 如何在 C++ 中打印 double

标签 c++ printing int double

我正在做一个 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/

相关文章:

c++ - 避免访问数组越界的最干净方法?

c++ - 如何为 OpenCV 多核图像处理创建 TBB 任务调度程序? C++

c# - 从头开始创建图形并返回它们以打印页面事件

angularjs - Node JS - 使用打印机(硬件)

java - 线程中的异常 "main"java.lang.NumberFormatException : For input string: "1"

php - 在php中将长度超过16位的int转换为字符串

c++ - 内存分配对多线程性能的影响

c++ - Windows XP 上高级格式硬盘的物理扇区大小

memory - 单击 CrViewer 打印按钮时出现 "Attempted to read or write protected memory.."错误

C++将int转换为具有未知基数的字符串的简单方法