Jim asks:
Ray, I'm just playing and can't figure this out.
Given:
<cffunction name="makeRandomNum" returntype="numeric" output="false">
<cfset var result = RandRange(0,10)>
<cfreturn result>
</cffunction>
<cfset num1 = makeRandomNum()>
<cfset num2 = makeRandomNum()>
<cfset Oper = mid("+-*", randRange(1,3),1)>
<cfset ans = num1 Oper num2>
How can I get var Oper reconized as mathical operator?
This is one of the few times where the evaluate function is necessary. In order to get ans to represent the right value, we can easily switch it to:
<cfset ans = evaluate("num1 #oper# num2")>
Of course, this isn't the only way. Since the number of mathematical operands are limited, you could always write a UDF that takes all 3 values (the two numeric value and the operand) and simply uses a switch case to determine which one to run. But that would be overkill and a complete waste of time, so only an idiot would do it.
<cfoutput>oper=#oper# num1=#num1# num2=#num2#, #evaluate("num1 #oper# num2")#<br></cfoutput> <cfscript>
function wasteOfTime(num1,num2,oper) {
switch(oper) {
case "+": return num1+num2;
case "-": return num1-num2;
case "": return num1num2;
case "/": return num1/num2;
}
return "NAN";
}
</cfscript>
<p>
<cfoutput>#wasteOfTime(num1,num2,oper)#</cfoutput>
<cffunction name="makeRandomNum" returntype="numeric" output="false">
<cfset var result = RandRange(0,10)>
<cfreturn result>
</cffunction>
<cfset num1 = makeRandomNum()>
<cfset num2 = makeRandomNum()>
<cfset Oper = mid("+-*", randRange(1,3),1)>
Enjoy.