解决方案
使用用户编写的函数,带有参数、局部变量以使其远离其他代码,并使用 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