About simple recursion code
조회 수: 2 (최근 30일)
이전 댓글 표시
this code isn't work with me. for example i want to calculate the odd number in 9 is 5 odd number
function d = oddn(n)
%this program calculate the odd numbers in a number
if n==0 | mod(n,2)==0
d=0
elseif mod(n,2)~=0
d=1
else
d=oddn(n-1)+oddn(mod(n,2))
end
댓글 수: 2
KALYAN ACHARJYA
2019년 12월 1일
편집: KALYAN ACHARJYA
2019년 12월 1일
"i want to calculate the odd number in 9 is 5 odd number"?
Can you clarify again?
채택된 답변
Turlough Hughes
2019년 12월 1일
편집: Turlough Hughes
2019년 12월 1일
As I understand it you want to find the number of odd numbers from 1 to n. You shouldn't need to write a function for this, you can simply write:
d=ceil(floor(n)/2);
I used floor n, to account for circumstances where n is not an integer.
댓글 수: 1
Turlough Hughes
2019년 12월 1일
If recursion is a requirement you could do the following:
function d = oddn(n)
if n<=0
d=0;
else
d=oddn(n-1)+mod(n,2);
end
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!