You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复C++中for语句问题并正确计算总分?

修复C++ Score类的循环逻辑并正确计算总分

我编写了如下C++ Score类代码:

class score {
private: 
    int marks; 
    int total;
public:
    score(){ marks = 0; total = 0; } 
    void getM(); 
    void tot(); 
    void displayM(); 
    void cinM();
};
void score::displayM(){ 
    cout << "The score is " << total << endl;
}
void score::getM(){ 
    for (int i = 0; i <= subjects; i++) 
        cout << "Enter the score of the subject " << i << endl; 
    cin >> marks;
}
void score::tot(){ 
    total = total + marks;
}

当前运行输出为:

Enter the score of the subject 0
Enter the score of the subject 1
Enter the score of the subject 2
Enter the score of the subject 3
Enter the score of the subject 4
Enter the score of the subject 5
// 输入任意数字后,只会输出 The score is 3

我期望的输出是:

Enter the score of the subject 0 3
Enter the score of the subject 1 3
Enter the score of the subject 2 1
Enter the score of the subject 3 3
Enter the score of the subject 4 3
Enter the score of the subject 5 2
The score is 15

请问如何让for语句正常工作,并正确计算总分?


问题分析与修复方案

存在的问题:

  1. subjects未定义:getM()函数中使用的subjects变量没有声明,程序无法识别循环次数。
  2. 循环逻辑错误:输出提示和输入分数的语句不在同一个循环块内,导致循环只重复输出所有提示,最后仅执行一次输入操作。
  3. 总分未实时累加:每次输入分数后没有调用tot()函数,导致总分只累加最后一次输入的分数。
  4. 输入格式不符期望:当前提示和输入分两行显示,不符合期望的同行输入格式。

修改后的完整代码:

#include <iostream>
using namespace std;

class score {
private: 
    int marks; 
    int total;
    int subjects; // 添加科目数量成员变量
public:
    // 构造函数初始化,可传入科目数量
    score(int sub = 5){ 
        marks = 0; 
        total = 0; 
        subjects = sub;
    } 
    void getM(); 
    void tot(); 
    void displayM(); 
};

void score::displayM(){ 
    cout << "The score is " << total << endl;
}

void score::getM(){ 
    // 循环遍历每个科目,把输入和提示放进循环体内
    for (int i = 0; i <= subjects; i++) { 
        cout << "Enter the score of the subject " << i << " "; 
        cin >> marks;
        tot(); // 每次输入后立即累加总分
    }
}

void score::tot(){ 
    total += marks; // 简化累加写法
}

// 测试代码
int main() {
    score s(5); // 初始化科目数量为5(对应0-5共6个科目)
    s.getM();
    s.displayM();
    return 0;
}

说明:

  • 新增subjects作为类的私有成员,通过构造函数传入科目数量,明确循环次数。
  • 将输入语句和tot()调用移入循环体内,确保每个科目都能完成输入和累加。
  • 调整输出提示的格式,在提示末尾添加空格,让用户输入的内容和提示在同一行,符合期望输出样式。
  • 简化tot()函数的累加写法为total += marks,逻辑不变但更简洁。

运行修改后的代码,即可得到你期望的输出效果。


内容的提问来源于stack exchange,提问作者Blahblah Blah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:10:37