Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 4 of 4

09062013, 12:43 PM #1
 Join Date
 Sep 2013
 Location
 Romania
 Posts
 1
 Thanks
 0
 Thanked 0 Times in 0 Posts
Create a function that calculates multiplication/division using addition and subtract
I'm a beginner in javascript, or any other programming language.
I have two functions
//
function sum(a,b){
return a + b;
}
function reduce(a,b){
return a  b;
}
I need to create another function, let's call it calculate, a function that gets a string argument, something like this "4*5", or "9/3". The calculate function will have to use additions, the sum function respectively, in order to calculate the multiplication, and subtractions, the reduce function, in order to calculate the division.
Can some one please give me some hints on how to do this ??
Thanks
09062013, 02:51 PM
#2
 Join Date
 Jan 2013
 Location
 Germany
 Posts
 578
 Thanks
 4
 Thanked 77 Times in 77 Posts
A few functions that might come in handy:
https://developer.mozilla.org/enUS/...s/String/split
https://developer.mozilla.org/enUS/...String/indexOf
Also, make sure to convert the numbers you collected from the string to actual Javascript numbers (i.e. using Number('5')), otherwise a+b will result in wrong results ('5' + '3' will evaluate to '53', not 8).
I'd call your reduce() function subtract() by the way, but that's up to you. Anyway, here is a skeleton to get you started:
Code:function multiply(input) { // do something to fill these variables with the corresponding values // make sure leftOperand and rightOperand are actually numerical values! var leftOperand, rightOperand, operationSymbol; // instead of if/elseif/else you could use a switch statement here (if you already know it) if(operationSymbol === "*") { // calculate multiplication } else if(operationSymbol === "/") { // calculate division } }
09062013, 03:55 PM
#3
 Join Date
 Jan 2011
 Location
 Missouri
 Posts
 4,029
 Thanks
 23
 Thanked 589 Times in 588 Posts
Hope this helps you also:
Code:<script type="text/javascript"> function sum(a,b){ return a + b; } function multiply (a,b){ var c = 0; for(i=1;i<=b;i++){ c += sum(a, 0); } return (c); } document.write('multiply 3 x 3 = '+multiply (3,3)); </script>
Evolution  The nonrandom survival of random variants.
09062013, 04:13 PM
#4
 Join Date
 Jan 2013
 Location
 Germany
 Posts
 578
 Thanks
 4
 Thanked 77 Times in 77 Posts
Edit: never mind.
Last edited by Airblader; 09062013 at 04:19 PM.