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

计算阿姆斯特朗数时While循环无法终止问题排查

问题原因与修复代码

你的代码陷入死循环且找不到阿姆斯特朗数,核心是两个逻辑错误:

  • 复用了初始数字的位数和各位值:while循环里计算result时,一直用的是输入数字的每一位(t(j))和初始位数l,但每次迭代的armstrong是新数字,必须重新获取它的位数和每一位来计算幂次和,不然永远得不到匹配的结果。
  • 循环终止条件逻辑混乱:while armstrong~=result的条件完全不成立,因为result是基于旧数字算出来的固定值,而armstrong一直在递增,永远不会相等,自然死循环。

修复后的代码如下:

input_num = input('请输入一个数字:');
% 先判断输入本身是否为阿姆斯特朗数
input_str = num2str(input_num);
digit_count = length(input_str);
sum_pow = 0;
for i = 1:digit_count
    sum_pow = sum_pow + str2double(input_str(i))^digit_count;
end
if sum_pow == input_num
    disp(input_num);
else
    candidate = input_num + 1;
    while true
        % 每次迭代都重新获取当前候选数的位数与各位数字
        candidate_str = num2str(candidate);
        current_digits = length(candidate_str);
        current_sum = 0;
        for j = 1:current_digits
            current_sum = current_sum + str2double(candidate_str(j))^current_digits;
        end
        if current_sum == candidate
            disp(candidate);
            break; % 找到目标后立即终止循环
        end
        candidate = candidate + 1;
    end
end

改动说明:

  1. 把变量int改成input_num,避免和Matlab内置类型关键字冲突
  2. 在while循环内部,每次都重新计算当前候选数的位数和各位的幂次和,确保计算的是当前候选数的阿姆斯特朗值
  3. 改用while true配合break的逻辑,找到符合条件的数就终止循环,逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:41:18