2014-03-14 84 views
1

要计算给定输入的平方根,所以我使用该代码平方根计算

var no1:Number = 2; 
var no2:Number; //input for calculation 
var total:Number; 
total=Math.pow(no2,(1/no1)); 

其工作,但我所面临的问题,例如: - 如果我给

二氧化氮= 25 ;

话,就说明

总= 4.9999999

来克服这个问题,我用下面的代码

总= Math.ceil(Math.pow(NO 2, (1/NO1)));

但它的okey为25。

总= 5

的问题是,如果我给21,22,23,24

所有此输入它显示5

所以是有任何其他的解决方案?? ?

回答

1

如果你想利用次方根。您可以养活你的函数的输出到任意取整函数是这样的:

/** 
* Rounds input number to specified number of decimal places. For example 
* round(4.568, 2) will return 4.57, and round(4.99, 2) will return 5. 
*/ 
function round(num:Number, toDecimalPlaces:uint) { 
    var factor:uint = Math.pow(10, toDecimalPlaces); 
    return Math.round(num * factor)/factor; 
} 

/** 
* Returns nth root to two decimal places. 
*/ 
function nthRoot(n:uint, num:Number) { 
    return round(Math.pow(num, (1/n)), 2); 
} 
+0

为√25.... rounded-result = 8.881784197001252e-16 ....所以我怎么能把它转换为0.000000000000001 @Peter – subrat71

+1

我实际上建议使用第二种解决方案而不是第一种。 :) – Peter

+0

thanx @Peter ....你救了我的时间...祝你有个美好的一天 – subrat71

1

There's a function for that

var total:Number = Math.sqrt(no2); 
+0

亚我知道,但我给NO1为变量,因为我想计算3√(NO2),4√(NO2),5√ (no2)..... – subrat71

+0

3√(no2)只是一个double sqrt,所以'Math.sqrt(Math.sqrt(no2))',4√(no2)是一个三元sqrt等等。迭代地对数字进行平方根并返回结果。 – Shannon

0

我实际的代码是这样

var str:String=view.numDisplay.text;//input string 
var power:Number = Number(inString.charAt(inString.indexOf('√') - 1));//to get the value before √ i.e no1 
var no1:Number; 
var no2:Number; 
var total:Number; 
if(power) 
    no1=v; 
else 
    no1=2; 
no2=getSubTerm();//method to find no2 it returns the number for calculation 
total=Math.ceil(Math.pow(no2,(1/no1)));