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

嵌套for循环实现两位数读取及数位求和问题咨询

解决打印两位数并计算数位和的问题

看起来你正在学习嵌套for循环,而且想实现一个打印所有两位数并计算数位和的程序,这个需求刚好能帮你吃透循环逻辑!我来帮你补全代码,同时给你一个贴合嵌套循环学习重点的实现版本。

首先,先补全你原本的思路:直接遍历10到99的所有数字,通过数学运算拆分十位和个位(不用转字符串,效率更高)。补全后的代码如下:

public class NestedLoops6 {
    public static void main(String[] args) {
        // 遍历所有两位数
        for(int counter = 10; counter < 100; counter++) {
            // 用整数除法取十位,取余运算取个位
            int tens = counter / 10;
            int units = counter % 10;
            int sum = tens + units;
            // 按照要求格式输出
            System.out.println(counter + ": " + tens + "+" + units + "=" + sum);
        }
    }
}

不过既然你想练习嵌套for循环,我们可以换一种更贴合学习目标的写法:用外层循环控制十位数字(1到9,因为两位数的十位不能为0),内层循环控制个位数字(0到9),通过嵌套循环生成所有两位数,同时计算数位和。代码示例:

public class NestedLoops6 {
    public static void main(String[] args) {
        // 外层循环:遍历十位数字(1-9)
        for(int tens = 1; tens <= 9; tens++) {
            // 内层循环:遍历个位数字(0-9)
            for(int units = 0; units <= 9; units++) {
                int number = tens * 10 + units;
                int sum = tens + units;
                System.out.println(number + ": " + tens + "+" + units + "=" + sum);
            }
        }
    }
}

这个嵌套循环的逻辑很直观:外层每迭代一次(十位加1),内层就会遍历所有可能的个位数字,生成从10-19、20-29直到90-99的所有两位数,完美覆盖需求,也能让你清晰感受到嵌套循环如何处理多维度的遍历场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:33:16