Sum of even numbers
조회 수: 25 (최근 30일)
이전 댓글 표시
this is what i was trying
function s = test(n)
if n <= 0 %for n<= 0 the result would be 0
s = 0;
elseif % if n is a decimal (positiv or neg. ) the result would be Nan
n ~= floor(n)
s=Nan; %not a number
else
sum(2:2:n) % Example( test(4) = 2+4=6, or test(6)=2+4+6=12)
end
it does not work, has anybody a suggestion ?
댓글 수: 0
답변 (2개)
Alan Stevens
2021년 5월 19일
편집: Alan Stevens
2021년 5월 19일
Like so
s = test(6);
disp(s)
function s = test(n)
if n <= 0 %for n<= 0 the result would be 0
s = 0;
elseif n ~= floor(n) % if n is a decimal (positiv or neg. ) the result would be Nan
s=NaN; %not a number
else
s = sum(2:2:n); % Example( test(4) = 2+4=6, or test(6)=2+4+6=12)
end
end
댓글 수: 0
Kartikay Sapra
2021년 5월 19일
function s = even_sum(n)
if n <= 0
s = 0
else if n~=floor(n)
s = NaN
else
s = sum(2:2:n)
end
end
Few suggestions:
- Nan is undefined, one should use NaN: Not a Number
- function name 'test' might clash with an inbuit function.
- In else condition, assign sum(2:2:n) to s
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Traveling Salesman (TSP)에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!