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

如何在C++的else分支中反转for循环实现降序输出?

C++书籍列表降序输出的正确实现

你的错误代码核心问题是数组下标越界:C++数组的下标从0开始,你定义的books数组有6个元素,合法下标范围是0~5。而你写的循环for (int i = 6; i > 0; i--)会先访问books[6],这属于越界访问,会触发未定义行为(可能输出乱码、程序崩溃等)。

修正后的else分支代码

直接调整循环的起始值和终止条件即可:

else{
    const char* books[6]
        = { "1 Literature", "2 Grammar", "3 Spelling", "4 Short Stories", "5 Alphabet", "6 Punctuations" };

    // 从最后一个元素的下标5开始,循环到0
    for (int i = 5; i >= 0; i--)
        cout << books[i] << "\n";

    return 0;
}

更优的代码结构(避免重复定义数组)

把books数组提到分支外面,让两个分支共用同一个数组,减少冗余代码:

#include <iostream>
using namespace std;

int main() {
    int a = 1;
    int ans = a;
    int inp;
    // 数组只定义一次,两个分支共用
    const char* books[6] = { "1 Literature", "2 Grammar", "3 Spelling", "4 Short Stories", "5 Alphabet", "6 Punctuations" };

    cout << "type 1 for ascending and 2 for descending\n \n" << endl;
    cin >> inp;

    if (inp == ans) {
        for (int i = 0; i < 6; i++)
            cout << books[i] << "\n";
        return 0;
    } else {
        for (int i = 5; i >= 0; i--)
            cout << books[i] << "\n";
        return 0;
    }
}

这样调整后,输入2时就会从最后一个元素开始输出,实现降序效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:55:22