window.addEventListener("DOMContentLoaded", function() {
var calculator = document.querySelector(".calculator"),
screen = document.querySelector(".screen");
var methods = {
firstNumber: 0,
secondNumber: 0,
"+": function() {
return this.firstNumber += this.secondNumber
},
"-": function() {
return this.firstNumber -= this.secondNumber
},
"*": function() {
return this.firstNumber *= this.secondNumber
},
"/": function() {
return this.firstNumber /= this.secondNumber
},
out: function(firstNumber) {
screen.innerHTML = firstNumber
},
fix: function(firstNumber) {
return (this[firstNumber] * 100 | 0) / 100
},
cur: 0,
res: function(firstNumber) {
if (firstNumber == +firstNumber)
if (!this.cur) {
this.firstNumber = +(this.firstNumber + "" + firstNumber);
this.out(this.fix("firstNumber"));
}
else {
this.secondNumber = +(this.secondNumber + "" + firstNumber);
this.out(this.fix("firstNumber") + this.cur + this.fix("secondNumber"));
}
else if (firstNumber == "c") {
this.secondNumber = this.firstNumber = this.cur = 0;
this.out(0);
}
else if (this.cur) {
if (!this.secondNumber && this.cur == "/") {
this.out("error");
return
}
!this.secondNumber && this.cur != "*" && (this.secondNumber = this.firstNumber);
this[this.cur]();
this.out(this.fix("firstNumber"));
this.secondNumber = 0;
this.cur = firstNumber == "=" ? 0 : firstNumber
}
else if (firstNumber != "=") {
this.out(this.fix("firstNumber") + firstNumber);
this.cur = firstNumber
}
}
};
calculator.addEventListener("click", function(event) {
var cls = event.target.classList;
if (cls && cls.contains("button")) {
val = event.target.value;
methods.res(val)
}
})
});
Нашел на просторах. Оформил html, css. Уж обрадовался что работает! А нет. Если ввести например 8+0, результат 16. А от любого числа отнять 0, будет 0. Где тут ошибка? Зато на 0 делить нельзя.