Sum of even numbers

6 ビュー (過去 30 日間)
Osman Ballhysa
Osman Ballhysa 2021 年 5 月 19 日
編集済み: Alan Stevens 2021 年 5 月 19 日
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 ?

回答 (2 件)

Alan Stevens
Alan Stevens 2021 年 5 月 19 日
編集済み: Alan Stevens 2021 年 5 月 19 日
Like so
s = test(6);
disp(s)
12
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

Kartikay Sapra
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:
  1. Nan is undefined, one should use NaN: Not a Number
  2. function name 'test' might clash with an inbuit function.
  3. In else condition, assign sum(2:2:n) to s

カテゴリ

Help Center および File ExchangePID Controller Tuning についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by