while loops and functions
    조회 수: 5 (최근 30일)
  
       이전 댓글 표시
    
I'm trying to get this function where the function repeats over and over until the user quits. Quiting the program would be done by inputing 0 and at that time the program would output the average number of guesses. 
function improvingguessing
%This function alows the user to guess what a random number is and keeps
%prompting them to continue guessing until they input the break key
%Output one random number.
    a=randi(20); 
%Displays text
    disp('I am thinking of a number between 1 and 20; input 0 to quit ')  
% Asks user to input a number 
    x=input('Input your guess \n');
%Sets counters equal to zero
    counta=0; 
    countb=0; 
%While x is not equal to 0 the following comands will be exucuted 
while x ~= 0 
%This classifies the user's input if the guess is above or below the program will tell the user their guess is incorrect
    if x > a
        counta = counta + 1;
        disp('You are to high, guess again');
        x=input('Enter a new guess \n');
    elseif x < a
        counta = counta +1;
        disp('You''re too low , guess again');
        x=input('Enter a new guess \n');
    elseif x==a
        countb= countb+1;  
        disp('Are you a Jedi? You guessed right!');
    end
end
while x == 0
    break;
   avg_g=counta/countb;
   fprintf("It took you %2.1f guesses", avg_g)
end
end
댓글 수: 2
답변 (1개)
  Walter Roberson
      
      
 2019년 3월 26일
        The x==a case needs a break
At the end, your x == 0 case can only be entered if the user entered 0, but then you immediately break so you never process the avg_g . If the user got the answer correct so x is not 0 then the second while will not be entered.
What is going on with your countb ? If the user enters 0 before they match, then countb will be left at 0, and when you calculate calculate avg_g (assuming you fix your code to get there) then that would lead to a division by 0. If the user matched before entering 0 then countb would have been incremented to 1, and a valid division by 1 would be used. But why bother with that division, why bother dividing by 1 ??
... or are you wanting to loop the whole guessing sequence until the user enters 0? If you did do that then it might indeed make sense to output the average number of guesses that the user needed. But if that is what you want, then you need to go back to choosing randomly and so on.
- initialize counta and countb
- while true
- choose a new number
- fetch a guess
- while the guess ~= 0
- tell the user how they did
- end inner while
- end outer while
댓글 수: 2
참고 항목
카테고리
				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!


