C++练习总分百分比程序问题:循环无法累计仅统计最后一次数据
问题分析与修复方案
你的代码核心问题是没有对总得分和总可能得分做累加操作:每次循环输入的得分s和总分t都会直接覆盖之前的值,最后输出的只是最后一次练习的数据,百分比也是单次练习的结果,自然无法统计所有练习的总和。
修改后的代码
#include <iostream> using namespace std; int main() { float s; // 当前练习得分 float t; // 当前练习总分 float p; // 总百分比 int n; // 练习次数 float total_score = 0; // 总得分,初始化为0 float total_total = 0; // 总可能得分,初始化为0 cout << "Enter the number of exercises to input: "<<endl; cin >> n; for (int i=1; i <=n; i++) { cout << "Enter the score received for Exercise " << i << endl; // 显示当前练习序号,更友好 cin >> s; cout << "Enter the total points possible for Exercise " << i << endl; cin >> t; // 累加当前练习的得分和总分到总变量中 total_score += s; total_total += t; } // 循环结束后计算总百分比 p = (total_score / total_total) * 100; cout << "your total is " << total_score << " out of "<< total_total << " or " << p << "%" << endl; return 0; }
关键修改点
- 新增
total_score和total_total两个变量,初始化为0,专门存储所有练习的得分总和与总分总和。 - 循环内不再直接计算单次百分比,而是将每次输入的
s和t累加到总变量中,保留所有练习的累计数据。 - 总百分比的计算移到循环结束后,用总得分除以总可能得分再乘以100,得到最终的整体百分比。
- 优化输入提示,显示当前练习的序号,提升用户操作体验。
内容的提问来源于stack exchange,提问作者Manda Lyons
相关产品推荐
相关产品推荐

