如何在C 中打印双重
How to print a double in C++
本文关键字:打印 更新时间:2023-10-16
我正在进行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 Gradept:345 GPA:3"
但是我期望的是"学生:783-92-4716单位:100 Gradept:345 GPA:3.45"
而不是在GPA中获得整数,我该如何获得双重?
而不是在GPA中获得整数,我该如何获得双重?
当您使用
时 int gpa;
gpa = double(gradepts)/units;
您正在截断double
。
如果要保持至少两个小数点,则可以使用:
double gpa(){
int gpa = 100*gradepts/units;
return gpa/100.0;
}
您可以通过包括操纵器来轻松地做。该操纵器在标题<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;
}
我希望这能解决您的问题。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数