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

如何在C++中不使用循环实现升序数字打印?

在C++中不使用循环打印升序数字的几种方法

方法1:递归实现(运行时动态范围)

递归是循环最直接的结构化替代,通过函数自身调用模拟迭代逻辑,完全不需要写循环语句,代码也简洁:

#include <iostream>

void printAscending(int start, int end) {
    // 终止条件:起始值超过结束值时停止
    if (start > end) return;
    std::cout << start << " ";
    // 递归调用,起始值自增1
    printAscending(start + 1, end);
}

int main() {
    printAscending(1, 10); // 打印1到10的升序数字
    return 0;
}

这个逻辑很清晰:先判断是否到达终止条件,若没到就打印当前值,再递归处理下一个数字,完全避免了一堆嵌套if else的混乱。

方法2:模板元编程(编译期固定范围)

如果打印的范围是编译期就能确定的常量,可以用模板元编程在编译期展开逻辑,运行时直接执行生成的代码,没有运行时递归或循环的开销:

#include <iostream>

// 通用模板:打印当前数字后递归处理下一个
template<int Current, int End>
struct PrintAscending {
    static void run() {
        std::cout << Current << " ";
        PrintAscending<Current + 1, End>::run();
    }
};

// 特化终止模板:打印最后一个数字后结束
template<int End>
struct PrintAscending<End, End> {
    static void run() {
        std::cout << End << std::endl;
    }
};

int main() {
    PrintAscending<1, 10>::run(); // 编译期确定1到10的范围
    return 0;
}

这种方式适合范围固定的场景,所有逻辑在编译期就处理完成,运行时只是执行打印操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 11:27:04