我的程序中的值计算不正确,即使支持数学是正确的
A value in my program is being calculated incorrectly, even though the supporting math is correct
在我的课程模块中,我们正在编写一个程序,询问班级名称,成绩和学分。在一定数量的类结束时,它要求我们使用 setprecision(2( 将 GPA 计算到小数点后 2 位。我的所有程序功能,除了,它计算 GPA 为 3.00 而不是 3.14。我的总积分达到 22,总积分为 7,因此在设定精度下它理应为 3.14。关于为什么我得到 3.00 的任何见解?任何帮助都值得赞赏,因为我对此很陌生。
#include iostream
#include iomanip
#include string
//I took out the < and > because it made the words disappear
using namespace std;
int main(){
cout<< std::fixed << std::setprecision(2);
int totalCredits = 0;
int gradePoints = 0;
string courseName;
cout<<"Enter a course name: ";
getline (cin, courseName);
cout<<courseName <<endl;
int credits;
cout<<"Enter number of credits: ";
cin>>credits;
cout<<credits <<endl;
totalCredits = totalCredits + credits;
string grade;
cout<<"Enter your grade (A, B, C, D, F): ";
cin>>grade;
cout<<grade <<endl;
if (grade == "A"){
gradePoints = gradePoints + (4.00 * credits);
}
else if (grade == "B"){
gradePoints = gradePoints + (3.00 * credits);
}
else if (grade == "C"){
gradePoints = gradePoints + (2.00 * credits);
}
else if (grade == "D"){
gradePoints = gradePoints + (1.00 * credits);
}
string answer;
cout<<"Continue ('Yes' or 'No')? ";
cin>>answer;
cout<<answer <<endl;
while (answer == "Yes"){
cout<<"Enter a course name: ";
cin.ignore();
getline (cin, courseName);
cout<<courseName <<endl;
cout<<"Enter number of credits: ";
cin>>credits;
cout<<credits <<endl;
totalCredits = totalCredits + credits;
cout<<"Enter your grade (A, B, C, D, F): ";
cin>>grade;
cout<<grade <<endl;
if (grade == "A"){
gradePoints = gradePoints + (4.00 * credits);
}
else if (grade == "B"){
gradePoints = gradePoints + (3.00 * credits);
}
else if (grade == "C"){
gradePoints = gradePoints + (2.00 * credits);
}
else if (grade == "D"){
gradePoints = gradePoints + (1.00 * credits);
}
cout<<"Continue ('Yes' or 'No')? ";
cin>>answer;
cout<<answer <<endl;
}
cout<<"Total grade points: " <<gradePoints <<endl;
cout<<"Total credits attempted: " <<totalCredits <<endl;
float gpa = 0;
gpa = gradePoints/totalCredits;
cout<<"Your GPA is " <<gpa <<endl;
return 0;
}
int 除以 int 得到一个 int。 通过在division 语句的变量名之前添加 (double( 来强制转换其中一个。
其他注意事项:
- 你几乎重复整个程序,只是为了确保它执行一次。您只需将答案设置为"是",您就知道它会执行。
- Cin <<变得非常挑剔。 通常最好使用
getLine()
并根据需要进行解析,更多信息。 (可能是家庭作业矫枉过正... 在这种情况下,快速修复使用ignore()
清除流,并使用clear()
重置流。 示例工作程序在这里。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 显示错误输出的简单数组排序程序
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 有人可以在下面的示例 C++ 程序中解释字符数组 KCHAR1 的奇怪行为吗?
- C ++程序如何返回我的数组或写入全局变量
- For 循环在尝试读取数组 c++ 时程序崩溃
- C++20 从括号中的值列表初始化聚合,不支持内部数组
- 由于 C++17 支持数组shared_ptr,这是否意味着在 ctor 和重置中不再需要 T[] 的显式删除器?
- 使用Microsoft安全支持提供程序接口 (SSPI) 对消息进行加密和签名
- C 中的回文数程序
- 无法使用 GCC 编译器 4.7.3 在 AIX 上编译具有线程支持的 c++ 程序
- 我支持的程序使用 SIGSEGV 崩溃,但我无法从.dmp文件中崩溃
- 令人困惑的斐波那契数程序
- 阵列分割错误在斐波那契数程序