Help with Loops and Switch cases and Mean

조회 수: 1 (최근 30일)
D Moton
D Moton 2019년 10월 11일
편집: Turlough Hughes 2019년 10월 11일
Write a program that prompts the User for if they would like to enter a real number. If yes, prompt the User for the real number. Continue to do this until the User enters “no” to the first question. After the User enters “no”, display the average of all the numbers entered.
This is what I have so far. I am confused and I need help. How do I keep asking a question for a string and keep repeating this process? Then how do I store all the numbers entered so I can find the mean?
Q=input('Would you like to enter a real number? (Yes or No) ','s');
switch Q
case 'Yes'
n=input('Enter a number: ');
Q=input('Would you like to enter a real number? (Yes or No) ','s');
while Q~= 'No'
n=input('Enter a number: ');
end
case 'No'
mean(,)
end

채택된 답변

prasanth s
prasanth s 2019년 10월 11일
here is the code
Q=input('Would you like to enter a real number? (Yes or No) ','s');
n=[];
switch Q
case 'Yes'
count=1;
while ~strcmpi(Q,'no')
n(count,1)=input('Enter a number: ');
Q=input('Would you like to enter a real number? (Yes or No) ','s');
count=count+1;
end
mean_out=mean(n)
case 'No'
end

추가 답변 (1개)

Turlough Hughes
Turlough Hughes 2019년 10월 11일
편집: Turlough Hughes 2019년 10월 11일
Hi Deriniece,
You could modify your code as follows:
Q='';
ii=1;
while ~strcmpi(Q,'No')
Q=input('Would you like to enter a real number? (Yes or No) ','s');
switch Q
case 'Yes'
n(ii)=input('Enter a number: ');
ii=ii+1;
case 'No'
disp(['The average input value is: ' num2str(mean(n))]);
end
end
Although this requires the user to have a case sensitive input.
strcmpi and if else statements will allow for case-insensitive inputs such as 'Yes', 'yes' and 'YES'
Q='';
ii=1;
while(1)
Q=input('Would you like to enter a real number? (Yes or No) ','s');
if strcmpi(Q,'Yes')
n(ii)=input('Enter a number: ');
ii=ii+1;
else
disp(['The average input value is: ' num2str(mean(n))]);
break
end
end
You might also like to consider using the following functions: menu(), inptdlg().

카테고리

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