필터 지우기
필터 지우기

Loop and input question

조회 수: 3 (최근 30일)
John Colley
John Colley 2015년 10월 11일
답변: Maneet Kaur Bagga 2022년 7월 5일
I need to create a loop that ask for s user inputed number and then adds odds number starting at 1 until target number is reached.
  댓글 수: 2
Image Analyst
Image Analyst 2015년 10월 12일
OK. Good luck with that. Feel free to post your code and ask a question after reading this if you need help.
Image Analyst
Image Analyst 2015년 10월 12일
What's an "odds number"? Do you mean odds, as in chance or probability? Maybe use rand() or randn(). Or did you mean "an odd number" like 1,3,5,7, etc.? If so, which number? Or do you need to ask the user for one?

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

답변 (2개)

Stalin Samuel
Stalin Samuel 2015년 10월 12일
%If you are trying to find the sum of all odd no's between 1 and s (i.e s is your limit )
prompt = 'What is the value of s? ';
s = input(prompt)
O_Sum = 1
for i = 2:s
if mod(i,2)
O_Sum = O_Sum +i
end
end
  댓글 수: 1
Stephen23
Stephen23 2015년 10월 12일
This is a very inefficient loop: only half of the iterations actually perform anything useful. Rather than wasting lots of iterations, MATLAB easily iterates only over the odd values only, which means that the if statement is also not required:
s = input('What is the value of s? ','s');
x = 0;
for k = 1:2:str2double(s)
x = x+k;
end
Of course the whole thing would in any case be much neater and faster by using MATLAB's code vectorization abilities, which reduces this task to one simple sum command:
sum(1:2:str2double(s))

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


Maneet Kaur Bagga
Maneet Kaur Bagga 2022년 7월 5일
As per my uderstanding you want to create a loop which asks for an input from the user and returns the sum of odd numbers between 1 and the input number. Please find the code below as a solution. Hope it helps!
x = 100
x = 100
% You can use x = input() to take input from the user
num_sum = sum(1:2:x)
num_sum = 2500

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by