Creating a function to output factorials.
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi I am trying to create a user defined function that will allow me to enter an integer and it will output the given factorial.
function [y] = fact(x)
clc
y=1;
for i=1:x
y=y*i;
end
disp(y)
This is it and it is working but I also need it to display an error message if it is a negative integer or non integer (e.g 8.5) and for it to also display 1 for factorial 0.
I have tried adding if statements in the loop for if x<0 etc. but I am getting the same answer which is just 1.
It works for positive integers just not the others.
Any thoughts?
댓글 수: 0
채택된 답변
Walter Roberson
2020년 4월 16일
if ~isnumeric(x) || ~isscalar(x) || x ~= fix(x) %x == fix(x) checks for integer
error('Oh, oh, oh, oh, oh!')
end
댓글 수: 3
Walter Roberson
2020년 4월 16일
Works for me:
if ~isnumeric(x) || ~isscalar(x) || x ~= fix(x) || x<0 %x == fix(x) checks for integer
error('Oh, oh, oh, oh, oh!')
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Special Functions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!