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

C++嵌套for循环查找完全数:如何单次输出提示并打印结果

如何实现完全数的统一行输出逻辑?

没问题,这个需求很好实现——核心思路是先把所有找到的完全数收集起来,再统一输出,而不是找到一个就打印一次。这样就能轻松实现你要的「一次提示语+同一行所有结果」的格式。

具体步骤:

  • 先初始化一个容器(比如列表、数组),用来存储所有找到的完全数
  • 在你的嵌套循环判断逻辑里,每当确认某个数是完全数时,不要立刻打印,而是把它添加到这个容器中
  • 等所有循环迭代完成后,再检查容器:
    • 如果容器不为空,就打印提示语,接着输出容器里的所有数(用空格分隔)
    • 如果为空,可以按需输出「未找到完全数」的提示

示例代码(Python)

假设你已经完成了完全数的判断逻辑,只需要修改输出部分:

# 定义查找范围
start = 1
end = 30
# 初始化列表存储完全数
perfect_numbers = []

for num in range(start, end + 1):
    if num == 1:
        continue  # 1不是完全数,直接跳过
    sum_divisors = 0
    # 你的真因数求和逻辑(已完成部分)
    for i in range(1, num):
        if num % i == 0:
            sum_divisors += i
    # 判断是否为完全数,是就加入列表
    if sum_divisors == num:
        perfect_numbers.append(num)

# 统一输出结果
if perfect_numbers:
    # 把列表转成空格分隔的字符串
    print(f"Perfect numbers: {' '.join(map(str, perfect_numbers))}")
else:
    print("No perfect numbers found in the given range.")

运行这段代码,输入范围1-30时,就会输出:

Perfect numbers: 6 28

如果是其他语言(比如C),思路一致

核心还是先收集再输出,这里给个简单的C语言示例:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int start = 1, end = 30;
    int *perfect_nums = NULL;
    int count = 0;

    for (int num = start; num <= end; num++) {
        if (num == 1) continue;
        int sum = 0;
        for (int i = 1; i < num; i++) {
            if (num % i == 0) sum += i;
        }
        if (sum == num) {
            // 动态扩容数组存储结果
            count++;
            perfect_nums = realloc(perfect_nums, count * sizeof(int));
            perfect_nums[count - 1] = num;
        }
    }

    // 输出处理
    if (count > 0) {
        printf("Perfect numbers: ");
        for (int i = 0; i < count; i++) {
            printf("%d ", perfect_nums[i]);
        }
        printf("\n");
    } else {
        printf("No perfect numbers found.\n");
    }

    free(perfect_nums);
    return 0;
}

这种方式的好处是逻辑清晰,输出格式完全可控,不管找到多少个完全数,都能统一按照要求输出。

内容的提问来源于stack exchange,提问作者Kenneth Steven McAusland Jr.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:28:38