问题
I'm making a calculator in javascript and as of now it calculates:
sin
, cos
, tan
, cot
, sec
, csc
and also arc
and hyberbolic
of all subtypes,
sqrt
, cbrt
, y-th root
, and pow
. The problem is that I dont want to have the pow(x,y)
as a function, I want to be able to type in for example:
2^3+2^4 # instead of pow(2,3)+pow(2,4)
How do I go about to get the function typed in as shown above? Here's the calculator for viewing it: http://calcy.comze.com/
回答1:
I assume you have the formula in a string. Here is how you can do it:
Extend the numbr proto to have a pow
method:
Number.prototype.pow = function(n){
return Math.pow(this,n);
}
wrap every number around ()
and replace ^
with .pow()
str = str.replace(/[\d|\d.\d]+/g, function(n){
return '(' + n + ')'
})
.replace(/\^/g, '.pow')
Eval the string
eval(str)
Working example: http://jsbin.com/igegok/1/edit
回答2:
You can transform your ^
notation to pow
function, or Math.pow
with regexp:
'2.14^3+ 2^2.5 - 12'.replace(/(\d+(?:\.\d+)?)\^(\d+(?:\.\d+)?)/g, function(a, b, c) {
return 'pow(' + b + ', ' + c + ')';
})
// pow(2.14, 3)+ pow(2, 2.5) - 12
With this approach you can even precalculate the power result and replace carots like this:
'2^3+ 2^2.5 - 12'.replace(/(\d+(?:\.\d+)?)\^(\d+(?:\.\d+)?)/g, function(a, b, c) {
return Math.pow(b, c);
});
// 8+ 5.656854249492381 - 12
来源:https://stackoverflow.com/questions/15037805/javascript-fixing-that-dan-caret-symbol-for-calculator