How to make a loop if a condition is not met
조회 수: 8 (최근 30일)
이전 댓글 표시
Hey my professor asked this question and I understand most of it except how to keep asking the user to input a valid number if the user enters 0. My code I already have is below.
In mathematics, sequences of numbers are seen regularly, many of which have defined patterns. A geometric sequence is one of the most common. In this sequence each subsequent number is calculated by multiplying the previous number by a defined ratio. This can be indicated by the equation below:
an = r*an-1
Where an indicates the nth term and r is the ratio. For example, if you have a starting value of 3 with a ratio of -2, you will get a sequence as follows:
3 -6 12 -24 48 -96 192 -384 768 -1536
You can see that each term is calculated by multiplying the previous term by -2 (the ratio), starting with the first term which is 3.
For this problem, write a script file that prompts the user to input the first term and ratio for a geometric sequence. It will then calculate the first 10 terms of the sequence and output this to the user as a vector. A geometric sequence cannot be created for a ratio or initial term of 0 so be sure to have the script produce an error if this is input and allow the user to try again and again until they input valid numbers.
a=input('Enter the starting value: ');
r=input('Enter the ratio for the function: ');
v=zeros(1,10);
v(1)=a;
n=1;
if a~=0
if r~=0
while n<10
a=r*a;
v(n+1)=a;
n=n+1;
end
end
end
disp(v)
Thank you, have a nice day!
댓글 수: 0
채택된 답변
KL
2017년 11월 22일
편집: KL
2017년 11월 22일
You have got it almost right but you have to have the while loop on top to ask the user untill non zero values are received. Inside the loop you can have an if-else statement to calculate your series or to throw an error message.
It's better to start with some initial values so,
a = 0; %zero first because while loop should be executed atleast once
r = 0;
n=10; %length of your sequence
v = zeros(1,n);
go to the loop now,
while a==0 || r==0
a=input('Enter the starting value: ');
r=input('Enter the ratio for the function: ');
if a~=0 && r~=0
v(1) = a; %go here only if they are non zero values
for k=2:n %loop to calculate your series
v(k) = r*v(k-1);
end
else %else throw an error message and loop will be continued
disp('error: please enter non zero values');
end
end
finally display the result with
disp(v)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!