まずは関数の定義のしかたと使い方を習得するために階乗のプログラムです。ここではForループでも良かったのですが、whileループとしました。
Scilab自体にfactorial()という関数があるので、ここではmyFactorialという関数名としました。引数を一つとり、この引数(int型)の階乗を計算してその値を返します。
Scilabのヘルプにも関数の使い方は載っており、参考としました。
14行目はデバックの目的で入れてあります。5の階乗を計算させていますが、ループが正しく回っていることがコンソール画面上で確認できます。
// Practice program to learn using a function
// The cunction 'factorial' returns the factorial value of the input
// Authoer: Nolan00267
// Date: July 15, 2014
clear;
function x=myFactorial(a)
x=1;
while (a > 1)
x=x*a;
a=a-1 ;
//Used 'disp(x)' for debugging purpose, but it can be commented out
disp(x);
end
endfunction
tt=myFactorial(5);
念のためforループでは次のようになりますが、同じように動作しているようです。
// Practice program to learn using a function
// The cunction 'factorial' returns the factorial value of the input
// Authoer: Nolan00267
// Date: July 15, 2014
function x=myfct(a)
x=1;
for i=1:1:a
x=x*i;
disp(x);
end
endfunction
tt=myfct(5)
まだまだ勉強途上なので何か間違いがあれば、その他アドバイスがあればぜひお願いします。
0 件のコメント:
コメントを投稿