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.

 채택된 답변

KSSV
KSSV 2021년 10월 27일

1 개 추천

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

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 2021년 10월 27일
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 2021년 10월 27일
Thank you! I was missing the p = p*x

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2021년 10월 27일

댓글:

2021년 10월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by