C++编写的班级出勤率计算程序输出始终为0,求问题排查解决方法
问题根源
程序输出始终为0是因为C++整数除法的截断规则:当两个int类型的数值做除法时,结果会直接舍弃小数部分只保留整数,只要class_attended < class_held,class_attended / class_held的计算结果就会是0,乘以100之后自然还是0。
修复方案
- 方案1:调整运算顺序(最简单,不需要修改变量类型)
把计算逻辑改成先乘100再做除法,避免提前出现小数被截断:
int class_attended_percentage = (class_attended * 100) / class_held;
- 方案2:转换为浮点型计算(可以保留小数精度)
如果需要输出带小数的出勤率,就把计算过程中的值转为浮点类型:
// 把结果变量改为double类型,计算时先把其中一个操作数转为double触发浮点除法 double class_attended_percentage = (static_cast<double>(class_attended) / class_held) * 100; // 输出的时候可以指定保留的小数位数,比如保留1位: cout << "你的出勤率为 " << fixed << setprecision(1) << class_attended_percentage << "%" << endl;
注意:使用
fixed和setprecision需要在代码开头引入头文件#include <iomanip>
完整可运行修复代码(带小数输出版本)
#include <iostream> #include <iomanip> using namespace std; /* 计算出勤率的程序 */ int main() { int class_held, class_attended; cout << "总共上了多少节课?" << endl; cin >> class_held; cout << "你出席了多少节课?" << endl; cin >> class_attended; double class_attended_percentage = (static_cast<double>(class_attended) / class_held) * 100; cout << "你的出勤率为 " << fixed << setprecision(1) << class_attended_percentage << "%" << endl; return 0; }
内容的提问来源于stack exchange,提问作者Rudraksha Paul
相关产品推荐
相关产品推荐

