My perfect number code keeps showing me error

Hi,I am doing a question where they ask me to display perfect numbers between 2 numbers from the user however I am having error with if(sum(test(mod(i,test)==0))==i) may I know whats the issue? thanks
clc
num1=input('Enter your first number:');
num2=input('Enter your second number:');
output=zeros(1,num2);
for i=num1:num2
if true
end
if(sum==num1)
fprintf('%d',num1);
end
test=1:i-1;
if(sum(test(mod(i,test)==0))==i)
output(i)=i;
end
end
output(output--0)=[]

2 个评论

What is sum ? There is typo error..either you should give some input to sum or replace it with variable.
I have placed a variable into sum however I'm still having error.May I know if I've placed my sum variable wrongly? clc
num1=input('Enter your first number:'); num2=input('Enter your second number:'); output=zeros(1,num2); for i=num1:num2 if true end sum=0; if(sum==num1) fprintf('%d',num1); end
sum=0;
test=1:i-1;
if(sum(test(mod(i,test)==0))==i)
output(i)=i;
end
end
output(output--0)=[]

请先登录,再进行评论。

回答(1 个)

You have the line
if (sum == num1) %() not needed. Matlab is not C
The only way this line would work is if sum is a scalar variable.
On the line
if (sum(...) == i) %again () not needed
you're either index into a vector variable called sum or more likely trying to call the sum function which is no longer visible to matlab since you've shadowed it with your sum variable. Either way it's not compatible with the previous line.
Morale of the story: don't use common function names (sum, mean, i, pi, etc.) as variable names.

类别

在 帮助中心 和 File Exchange 中查找有关 Graphics Object Properties 的更多信息

提问:

2017-9-26

评论:

2017-9-26

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by