本文介绍了与使用“查找"命令相比,该命令又如何呢?更改为“如果"和“用于"循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定n3 − n2 + 40大于1000并且n不能被3整除的1至50之间的所有整数.然后解决以下问题:1到50之间的整数是否完美(即它们等于它们的因子之和)?本书给出了以下代码

To determine all integers between 1 and 50 for which n3 − n2 + 40 is greater than 1000 and n is not divisible by 3. And then solve the question: Are any integers between 1 and 50 perfect (that is, are they equal to the sum of their factors)? The book gives the following code

n = 1:50;
       f = n.^3-n.^2+40;
       ii = find(f > 1000 & mod(n,3) ~= 0);
n(ii)

但是我只想使用"for"和"if"循环来更改此代码.有人可以帮我更改此代码吗?

But I want to change this code only using a "for" and "if" loops. Can someone help me to change this code please?

非常感谢.

推荐答案

n = 1:50;
f = n.^3-n.^2+40;
results = [];
for num = n //let's get into n
    if f(num) > 1000 & mod(num,3) ~= 0
        results(end+1) = num; //store the result into an array
    end
end

这很容易,但是find在这里看起来更合适.

It is very easy, but find looks like a better fit here.

这篇关于与使用“查找"命令相比,该命令又如何呢?更改为“如果"和“用于"循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:38