About simple recursion code

2 vues (au cours des 30 derniers jours)
Shahad Alsabi
Shahad Alsabi le 1 Déc 2019
Commenté : Turlough Hughes le 1 Déc 2019
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 commentaires
KALYAN ACHARJYA
KALYAN ACHARJYA le 1 Déc 2019
Modifié(e) : KALYAN ACHARJYA le 1 Déc 2019
"i want to calculate the odd number in 9 is 5 odd number"?
Can you clarify again?
Shahad Alsabi
Shahad Alsabi le 1 Déc 2019
I mean,how many 'odd' numbers do nine contains by using recursion.Which is this code is finding the odd number in any number.

Connectez-vous pour commenter.

Réponse acceptée

Turlough Hughes
Turlough Hughes le 1 Déc 2019
Modifié(e) : Turlough Hughes le 1 Déc 2019
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 commentaire
Turlough Hughes
Turlough Hughes le 1 Déc 2019
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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by