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

C++初学者求助:成绩评级程序输出异常问题排查

问题排查与修复:C++成绩等级输出异常

嘿,我一眼就看到你代码里的问题了——你试图把字符串字面量和整数直接相加,这在C++里的行为完全不是你预期的字符串拼接!

为什么输出会异常?

在C++中,像"You have earned an A"这样的字符串字面量本质上是一个const char*(指向字符数组的指针)。当你写"xxx" + score时,编译器会把这个操作理解为指针地址偏移:它会把字符串的起始地址往后移动score个字节,然后输出从这个偏移位置开始的内存内容。比如如果score是90,那相当于直接跳过字符串的前90个字符,而原字符串根本没那么长,结果自然是乱码、截断或者直接输出空内容。

怎么修复?

最直接的方法是利用cout的链式输出特性,把字符串和数字分开传给cout,它会自动帮你处理不同类型的输出拼接:

cout << "You have earned an A" << score;

另外,我还帮你优化了代码的健壮性,比如增加输入合法性检查,简化最后一个分支的逻辑,下面是完整的修正代码:

#include <iostream>
using namespace std;

int main() {
    int score;
    cout << "Enter your score (0-100): ";
    cin >> score;

    // 先检查输入是否在合法范围内
    if (score < 0 || score > 100) {
        cout << "Invalid score! Please enter a number between 0 and 100." << endl;
        return 1;
    }

    if (score >= 90 && score <= 100){
        cout << "You have earned an A (score: " << score << ")" << endl;
    }else if(score >= 80 && score <= 89) {
        cout << "You have earned a B (score: " << score << ")" << endl;
    }else if(score >= 70 && score <= 79) {
        cout << "You have earned a C (score: " << score << ")" << endl;
    }else if(score >= 60 && score <= 69) {
        cout << "You have earned a D (score: " << score << ")" << endl;
    }else { // 剩下的必然是0-59分,不用再判断范围
        cout << "You have earned an F (score: " << score << ")" << endl;
    }
    return 0;
}

额外说明

  • 如果你想用字符串拼接的方式(而不是链式输出),可以先把字符串字面量转换成std::string对象,再结合std::to_string()把整数转成字符串来拼接,比如:
    cout << string("You have earned an A") + " (score: " + to_string(score) + ")" << endl;
    
    不过这种写法不如链式输出简洁高效,一般推荐用前者。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:07:10