水仙花数是指一个 n 位数 ( n≥3 ), 它的每个位上的数字的 n 次幂之和等于它本身。我们可以使用MATLAB编写一个程序来找出所有的三位水仙花数。

for num = 100:999
    % 提取百位数字
    hundreds = floor(num / 100);
    % 提取十位数字
    tens = floor((num - hundreds*100) / 10);
    % 提取个位数字
    units = num - hundreds*100 - tens*10;
    
    % 判断是否为水仙花数
    if num == hundreds^3 + tens^3 + units^3
        disp(num);
    end
end

这个程序会输出所有的三位水仙花数,即153、370、371和407。


原文地址: https://www.cveoy.top/t/topic/hXzi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录