for command display too much info

I have been messing with this code for about an hour now and I am really close to being done. My problem is in fprintf I believe. I just want the last line to display. Here is my code.
int = input('Enter a number between 1 and 25: ');
if (int<1)||(int>25)
int = input('Invalid number enter another between 1 and 25: ');
end
fact = 1;
for i=int:-1:2;
fact = fact *i;
fprintf('The factoral of %g is %g\n',int,fact);
end
Also, I know there is a factoral command but my professor does not want us using it.
I have one more small thing that has been bugging me. We are supposed to ask the user if they are done and end the program if the user types y or Y. I'm just not sure how to get the program to identify a capital letter as well as lower case. I thought it would be something like this but it does not work.
done = input('Are you done? Type y for yes. ','s');
while done~='y'||done~='Y'
Thanks for any help everyone!

댓글 수: 1

Guillaume
Guillaume 2014년 10월 4일
I'm not sure what the title of the question has got to do with your actual question.

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

답변 (2개)

Guillaume
Guillaume 2014년 10월 4일

0 개 추천

There are many ways to do this, one possibility:
while true
%your code here
done = input('Are you done? Type y for yes. ','s');
if done == 'y' || done == 'Y'
break %terminate while loop
end
end
If you don't like that while true you could also do:
done = 'N'; %so it goes through the loop at least once.
while done ~= 'y' && done ~= 'Y'
%your code
done = input('Are you done? Type y for yes. ','s');
end
Image Analyst
Image Analyst 2014년 10월 4일

0 개 추천

Close, but you need two while loops. One to ask if they want to do it again, and one to keep asking until they enter a valid number that is in the required range. Here, try this:
clc;
% Initialize some things.
int = -1;
done = 'n';
% Loop over asking if they want to continue.
% Enter loop if done is not 'Y' or 'y'
while ~strcmpi(done, 'y')
% Loop over getting a valid (in range) number.
while (int<1)||(int>25)
int = round(input('Enter a number between 1 and 25: '));
if (int<1)||(int>25)
int = input('Invalid number enter another between 1 and 25: ');
end
end
fact = 1;
for k = int : -1 : 2;
fact = fact * k;
end
fprintf('The factorial of %g is %g\n',int,fact);
done = input('Are you done? Type y for yes, or n to continue: ','s');
% Reset int so next time we'll ask again.
int = -1;
end

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

질문:

2014년 10월 4일

답변:

2014년 10월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by