フィルターのクリア

Recursive Factorial Function Evaluation

2 ビュー (過去 30 日間)
Student
Student 2018 年 3 月 20 日
編集済み: Varsha Lohani 2021 年 10 月 23 日
I'm trying to make a recursive function to test factorials that will check for a variable that is a non-negative single argument (it will display an error using the error function if not). How should I go about doing this?

回答 (1 件)

Varsha Lohani
Varsha Lohani 2021 年 10 月 23 日
編集済み: Varsha Lohani 2021 年 10 月 23 日
clc
clear all
%% Factorial of the number
n = 8;
out = facto(n);
%% Factorial function
% Create a function for factorial
function f = facto(num)
% FACTO Summary of this function goes here
% factorial of the n
% It is a recursive function call
% if n does not reaches 0. This mean n is either negatve number or
% decimal number. The problem of out of memory occurs. The likely cause
% is an infinite recursion with the program. The problem never converges.
if ~isscalar(num) || num ~= fix(num) || num < 0
error('non-negative integer scalar input expected')
end
if num == 0
f = 1;
else
f = num*facto(num-1);
end
end

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by