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?

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 16 Apr. 2020

0 Stimmen

if ~isnumeric(x) || ~isscalar(x) || x ~= fix(x) %x == fix(x) checks for integer
error('Oh, oh, oh, oh, oh!')
end

3 Kommentare

MILLER BIGGELAAR
MILLER BIGGELAAR am 16 Apr. 2020
I am sorry but when fact(-x) (when x is a negative integer) i still receive the answer of 1 and not error, I have tried adding || x<0 after the if statement but this has not worked.
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
MILLER BIGGELAAR
MILLER BIGGELAAR am 16 Apr. 2020
I got it to work, I put the if statement after the factorial when I needed to put it before.
Much appreciated.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Debugging and Improving Code finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by