解決方案
使用使用者編寫的函數,帶有參數、局部變數以使其遠離其他程式碼,並使用 return 語句發回答案。
// this example shows how to write a user written function to roll
// ndice with nsides
// a user written function is created with an assignment statement
// to a variable that will be the name of the function. rollDice
// seems a good name to explain what this function does.
rollDice = Function( {ndice = 2, nsides = 6}, // parameters
{i, sum = 0}, // local variables
For( i = 1, i <= ndice, i++, // loop to add up the rolls
sum += Random Integer( 1, nsides ) // one roll
); // end of the loop
Return( sum ); // value to return
); // end of the definition
// make table and distributions. the number of dice
// and the number of sides is chosen to make the
// average roll be 36
dt = New Table( "Untitled",
Add Rows( 10000 ),
// each column has a formula that calls the function...
New Column( "one", Formula( rollDice( 1, 71 ) ) ),
New Column( "two", Formula( rollDice( 2, 35 ) ) ),
New Column( "three", Formula( rollDice( 3, 23 ) ) ),
New Column( "four", Formula( rollDice( 4, 17 ) ) )
);
// check the Std Dev in the 4 reports...
// it gets smaller with more dice
dt << Distribution(
Continuous Distribution( Column( :one ) ),
Continuous Distribution( Column( :two ) ),
Continuous Distribution( Column( :three ) ),
Continuous Distribution( Column( :four ) ),
SendToReport(
Dispatch( {"one"}, "Distrib Histogram", FrameBox, {DispatchSeg( Hist Seg( 1 ), Bin Span( 24, 0 ) )} ),
Dispatch( {"two"}, "Distrib Histogram", FrameBox, {DispatchSeg( Hist Seg( 1 ), Bin Span( 24, 0 ) )} ),
Dispatch( {"three"}, "Distrib Histogram", FrameBox, {DispatchSeg( Hist Seg( 1 ), Bin Span( 24, 0 ) )} ),
Dispatch( {"four"}, "Distrib Histogram", FrameBox, {DispatchSeg( Hist Seg( 1 ), Bin Span( 24, 0 ) )} )
)
);<BR />
討論
Function() 函數傳回一個函數。 Function() 的第一個參數是參數列表,並且是必需的。 如果沒有參數,請使用 {}。 參數可以有預設值,如上所示; rollDice() 將使用兩個 6 面骰。 rollDice(3) 將使用三個 6 面骰子,rollDice(1,7) 使用一個 7 面骰子。
函數的第二個參數是可選的局部變數列表,可以有初始值。 透過使用局部值,您可以讓函數呼叫其他函數,而不必擔心在 for 迴圈中重複使用「i」。 如果不需要指定局部變量,只需將函數體作為第二個參數而不是第三個參數即可。
最後一個參數(第二個或第三個)是函數體。 如果需要,它可以引用全域值。 您可以在正文中的任何位置使用 return 語句來指定要傳回呼叫方的值。 如果沒有 return 語句,則傳回最後執行的語句的值。
函數 rollDice 在第一次定義時不會被執行。 當使用參數呼叫它時會執行它,例如
rollDice(3,6)
此範例在列公式中執行的操作。
也可以看看
http://www.jmp.com/support/help/Advanced_Programming_Concepts.shtml