Creating a script that will allow the user to input values repeatedly until each case has been entered
Afficher commentaires plus anciens
I'm trying to create a script that will allow the user to input x-values repeatedly until each case has been entered. I have three possible cases: Case 1 is entered when x<=7, case 2 is entered when 712. I want to use a while statement to error-check the user input, ensuring that x>0. Each time a case is entered, I want to print the case number & the created y-value (y = x^3 + 3 for case 1, y = (x-3)/2 for case 2, and y = 4*x+3 for case 3). No case may be ran twice (then the script will output something like 'That case has been run already'). Once all cases have been entered, I want to print something like 'All cases have been entered'.
Here's the script I have so far & I'm stuck:
x = input('Please enter an x value > 0: ');
while x < 0
x = input('Invalid! Please enter another x value > 0: ');
end
counter1 = 0;
counter2 = 0;
counter3 = 0;
if x<=7
counter1 = counter1 + 1;
y = x.^3 + 3;
fprintf('Case 1: y = %d \n',y);
elseif 7<x || x<=12
counter2 = counter2 + 1;
y = (x-3)./2;
fprintf('Case 2: y = %d \n',y);
elseif x>12
counter3 = counter3 + 1;
y = 4.*x+3;
fprintf('Case 3: y = %d \n',y);
end
if counter1==0 || counter2==0 || counter3==0
x = input('Please enter an x value > 0: ');
elseif counter1>=1 || counter2>=1 || counter3>=1
disp('That case has been run already')
elseif counter1==1 && counter2==1 && counter3==1
disp('All cases have been entered!')
end
Réponse acceptée
Plus de réponses (1)
You haven't said what you are stuck with, but a few points that immediately come to mind:
- You are only looping on user input if the user enters a number < 0, otherwise you only ask them once and then once again at the end. You need a loop covering the whole thing, but with an exit condition.
- Your second case should have an && not a || otherwise the final elseif will never be reached.
- You shouldn't need an elseif for the final case, a simple else should do the job since it is the only case remaining.
- You should do your counter checking before handling the cases I assume, otherwise you still do the maths anyway then tell the user the case was already run afterwards.
- Your final elseif clause should form the exit condition from the all-enclosing while loop I mentioned above if you want the user to keep entering values until that clause is true.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!