法演算
Posted feedbacks - JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | normalize_law = function( law ){
return function(num){
num %= law;
num += num < 0 ? law : 0;
return num;
}
}
opfunc = (function(){
var func = {
'+' : function(x,y){return x+y },
'-' : function(x,y){return x-y },
'*' : function(x,y){return x*y }
};
return function(opcode){ return func[opcode]; };
})();
calc = function( exp, law ){
if( ! exp.match(/(-?\d+)\s*([-*+])\s*(-?\d+)/) ){
return null;
}
var ope1 = RegExp.$1;
var opcode = RegExp.$2;
var ope2 = RegExp.$3;
var normalize = normalize_law( law );
var opcode = opfunc(opcode);
return opcode
? normalize( opcode( normalize(ope1), normalize(ope2) ))
: null;
}
alert( calc("1+2",10) );
alert( calc("7 + 3",10) );
alert( calc("11 + 12",10) );
alert( calc("3 - 2",10) );
alert( calc("2 - 3",10) );
alert( calc("2 * 3",10) );
alert( calc("11 * 12",10) );
alert( calc("18 * 39",10) );
alert( calc("6 / 2",10) );
|


ihag
#4808()
Rating2/2=1.00
ここでいう法演算とは,与えられた数(ここでは「法」と言います)で剰余をとりながら行う計算のことです.たとえば,法が10である場合,以下のように計算します.
式と法を与えたときに,このような法演算を行い,計算結果を表示するプログラムを作成してください.
注意点
プログラムの出力として,計算結果を表示して下さい.
[ reply ]