I am trying to write a script that will find the product of all odd numbers that count up to a user input value. How can I write the code to identify the odd digits? If the user entered 8 I need to be able to single out the values of 1 3 5 7 to the multiply together.

 Akzeptierte Antwort

KSSV
KSSV am 27 Okt. 2021

1 Stimme

n = 8 ;
x = 1:n ;
idx = mod(x,2)
idx = 1×8
1 0 1 0 1 0 1 0
odd_nus = x(logical(idx))
odd_nus = 1×4
1 3 5 7

4 Kommentare

and finally do product
n = 8 ;
x = 1:n ;
idx = mod(x,2) ;
odd_nus = x(logical(idx))
odd_nus = 1×4
1 3 5 7
Product_Value = prod(odd_nus)
Product_Value = 105
Emma Rash
Emma Rash am 27 Okt. 2021
This helped a lot thank you so much! Do you happen to know why I cant put it into a for loop? It works perfectly until I add the for statement
n = 8 ;
p = 1 ; % product
for x = 1:n ;
if mod(x,2)
p = p*x ;
end
end
p
p = 105
Emma Rash
Emma Rash am 27 Okt. 2021
Thank you! I was missing the p = p*x

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 27 Okt. 2021

Kommentiert:

am 27 Okt. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by