Цитата:
Заранее очень благодарен! |
Кто может помочь собрать калькулятор бесплатно на форуме или платно ($/час) в скайпе (hbsv-mtt):
<form name="taschenrechner" id="calculator"> <table> <tr> <td> <input type="text" id="input" name="input" size="16" class="display"> </td> </tr> <tr> <td class="buttons"> <input type="button" id="btn_1" value="1" OnClick="addInput(1)"> <input type="button" id="btn_2" value="2" OnClick="addInput(2)"> <input type="button" id="btn_3" value="3" OnClick="addInput(3)"> <input type="button" id="add" value="+" onclick="addOperator('+')"> <br> <input type="button" id="btn_4" value="4" OnClick="addInput(4)"> <input type="button" id="btn_5" value="5" OnClick="addInput(5)"> <input type="button" id="btn_6" value="6" OnClick="addInput(6)"> <input type="button" id="sub" value="-" OnClick="addOperator('-')"> <br> <input type="button" id="btn_7" value="7" OnClick="addInput(7)"> <input type="button" id="btn_8" value="8" OnClick="addInput(8)"> <input type="button" id="btn_9" value="9" OnClick="addInput(9)"> <input type="button" id="mult" value="x" OnClick="addOperator('*')"> <br> <input type="button" id="clear" value="c" onClick="clear()"> <input type="button" id="btn_0" value="0" OnClick="addInput(0)"> <input type="button" id="calculate" value="=" OnClick="calc()"> <input type="button" id="div" value="/" OnClick="addOperator('/')"> </td> </tr> </table> </form> /** * Created by hbsv on 31.01.2016. */ var a,b,c; var action = ''; var input = document.getElementById('input'); function addInput(x) { var res = document.getElementById(x).value - ''; if (!isNaN(res)) return res; } function PutNum(val) { document.getElementById('input').value = (document.getElementById('input').value + val); } function add(a,b) { action = '+'; a = addInput('input'); document.getElementById('input').value = (a + b); return (a + b); function sub(a,b) { action = '-'; a = addInput('input'); document.getElementById('input').value = (a - b); return (a + b); } function mult(a,b) { action = '*'; a = addInput('input'); document.getElementById('input').value = (a * b); return (a * b); } function div(a,b) { action = '/'; a = addInput('input'); document.getElementById('input').value = (a / b); return (a / b); } function clear() { document.getElementById('input').value = ''; } function calculate() { b = addInput('input'); switch (action) { case '+': c = a + b; break; case '-': c = a - b; break; case '*': c = a * b; break; case '/': c = a / b; break } document.getElementById('input').value = c; } Очень нужна помощь, нужно собрать калькулятор при этом научиться самому его собирать )) Заранее Оч. Благодарен! |
Или еще лучше, с помощью методов
function Calculator() { var methods = { "+" : function(a,b) { return a + b; }, "-" : function(a,b) { return a - b; }, "*" : function(a,b) { return a * b; }, "/" : function(a,b) { return a / b; } } } |
Вот вроде сделал
<!DOCTYPE html> <html> <head> <title>Calc</title> <script type="text/javascript"> var calcString = ""; function control(testString) { testString = testString.replace(/\++/g, "+"); testString = testString.replace(/\--/g, "+"); testString = testString.replace(/\.\./g, "."); testString = testString.replace(/[+-][-+]/g, "-"); return testString; } function calculation(buffString) { buffString = buffString.replace(/([^[0-9.]{1})/g, " $1 ").trim(); // добавим пробелы вокруг не чисел buffString = buffString.replace(/ {1,}/g, " "); // удаление сдвоенных пробелов var buffArray = buffString.split(/\s/); // Элементы - в массив var polishString = new Array; var polishStack = new Array; var stringId = -1; var stackId = -1; for (var i = 0; i < buffArray.length; i++) { // формируем обратную польскую запись switch (buffArray[i]) { case "(": stackId++; polishStack[stackId] = buffArray[i]; break; case ")": while (stackId >= 0 && polishStack[stackId] != "(") { stringId++; polishString[stringId] = polishStack[stackId]; stackId--; } stackId--; break; case "+": while (stackId >= 0 && (polishStack[stackId] == "+" || polishStack[stackId] == "-" || polishStack[stackId] == "*" || polishStack[stackId] == "/")) { stringId++; polishString[stringId] = polishStack[stackId]; stackId--; } stackId++; polishStack[stackId] = buffArray[i]; break; case "-": while (stackId >= 0 && (polishStack[stackId] == "+" || polishStack[stackId] == "-" || polishStack[stackId] == "*" || polishStack[stackId] == "/")) { stringId++; polishString[stringId] = polishStack[stackId]; stackId--; } stackId++; polishStack[stackId] = buffArray[i]; break; case "*": while (stackId >= 0 && (polishStack[stackId] == "*" || polishStack[stackId] == "/")) { stringId++; polishString[stringId] = polishStack[stackId]; stackId--; } stackId++; polishStack[stackId] = buffArray[i]; break; case "/": while (stackId >= 0 && (polishStack[stackId] == "*" || polishStack[stackId] == "/")) { stringId++; polishString[stringId] = polishStack[stackId]; stackId--; } stackId++; polishStack[stackId] = buffArray[i]; break; default: stringId++; polishString[stringId] = buffArray[i]; } } while (stackId >= 0) { stringId++; polishString[stringId] = polishStack[stackId]; stackId--; } // польская запись готова // alert(polishString); stackId = -1; // Начинаем считать по польской записи var stringIdMax = stringId; for (stringId = 0; stringId <= stringIdMax; stringId++ ) { switch (polishString[stringId]) { case "+": stackId--; polishStack[stackId] = polishStack[stackId] + polishStack[stackId + 1]; break; case "-": stackId--; polishStack[stackId] = polishStack[stackId] - polishStack[stackId + 1]; break; case "*": stackId--; polishStack[stackId] = polishStack[stackId] * polishStack[stackId + 1]; break; case "/": stackId--; polishStack[stackId] = polishStack[stackId] / polishStack[stackId + 1]; break; default: stackId++; polishStack[stackId] = parseFloat(polishString[stringId]); } } return polishStack[stackId]; } function kalk() { try { var res = calculation(calcString); } catch (e) { res = "Ошибка в выражении"; } document.getElementById("res").innerHTML = calcString + "=" + res; } function addToInput(value) { calcString += value; calcString = control(calcString); document.getElementById("res").innerHTML = calcString; } function clean() { calcString = ""; document.getElementById("res").innerHTML = calcString; } function del() { calcString = calcString.substr(0,calcString.length - 1); document.getElementById("res").innerHTML = calcString; } </script> </head> <body> <table> <tr> <td> <div id="res" style="width:400px;min-height:20px;border:solid 1px black;"> </div> </td> </tr> <tr> <td class="buttons"> <div id="num1" align="center"> <input type="button" onclick="addToInput(this.value)" name="rakam11" value="1" /> <input onclick="addToInput(this.value)" type="button" name="rakam22" value="2" /> <input onclick="addToInput(this.value)" type="button" name="rakam33" value="3" /> <input onclick="addToInput(this.value)" type="button" name="rakam44" value="4" /> <input onclick="addToInput(this.value)" type="button" name="rakam55" value="5" /> <input onclick="addToInput(this.value)" type="button" name="rakam66" value="6" /> <input onclick="addToInput(this.value)" type="button" name="rakam77" value="7" /> <input onclick="addToInput(this.value)" type="button" name="rakam88" value="8" /> <input onclick="addToInput(this.value)" type="button" name="rakam99" value="9" /> <input onclick="addToInput(this.value)" type="button" name="rakam00" value="0" /> <input onclick="addToInput(this.value)" type="button" name="rakam00" value="." /> </div> <div id="act" align="center"> <input onclick="addToInput(this.value)" type="button" name="plus" value="+" /> <input onclick="addToInput(this.value)" type="button" name="minus" value="-" /> <input onclick="addToInput(this.value)" type="button" name="umn" value="*" /> <input onclick="addToInput(this.value)" type="button" name="divide" value="/" /> <input onclick="addToInput(this.value)" type="button" name="lpar" value="(" /> <input onclick="addToInput(this.value)" type="button" name="rpar" value=")" /> </div> </td> <tr> <td ><input type="button" name="button" id="button" onclick="kalk()" value="Считать" /> <input type="button" name="button1" onclick="clean()" value="CLEAN" /> <input type="button" name="button1" onclick="del()" value="DEL" /></td> </tr> </table> </body> </html> Осталась масса простору для доработок |
Спасибо Огромнейшее!
|
Если есть возможность подскажите еще пару вопросов:
Имеется калькулятор: <from id = 'calculator'> <table> <tr> <td> <div align="center"> <input id="screen" type="text" value="" size="16" class="display" readonly="readonly" /> </div> </td> </tr> <tr> <td class="buttons"> <div align="center"> <input id="btn_1" type="button" value="1" /> <input id="btn_2" type="button" value="2" /> <input id="btn_3" type="button" value="3" /> <input id="add" type="button" value="+" class="operator" /> </div> <div align="center"> <input id="btn_4" type="button" value="4" /> <input id="btn_5" type="button" value="5" /> <input id="btn_6" type="button" value="6" /> <input id="sub" type="button" value=" - " class="operator" /> </div> <input id="btn_7" type="button" value="7" /> <input id="btn_8" type="button" value="8" /> <input id="btn_9" type="button" value="9" /> <input id="mult" type="button" value=" * " class="operator" /> <div align="center"> <input id="clr" type="button" value=" c " class="clear" /> <input id="btn_0" type="button" value="0" /> <input id="calculate" type="button" value=" = " class="eval" /> <input id="div" type="button" value=" / " class="operator" /> </div> </td> </tr> </table> </from> var a,b,c; var action = ''; function getValue(id) { var res = document.getElementById(id).value - ''; if (!isNaN(res)) return res; } function PutNum(val) { document.getElementById("screen").value = (document.getElementById("screen").value + val)-0; } function add () { a = getValue("screen"); document.getElementById("screen").value = 0; action = "+"; } function sub() { a = getValue("screen"); document.getElementById("screen").value = 0; action = "-"; } function mult() { a = getValue("screen"); document.getElementById("screen").value = 0; action = "*"; } function div() { a = getValue("screen"); document.getElementById("screen").value = 0; action = "/"; } function clr() { document.getElementById("screen").value = 0; } function calculate() { b = getValue("screen"); switch(action) { case "+": c = a + b; break; case "-": c = a - b; break; case "*": c = a * b; break; case "/": if (b == 0) { alert('Division durch Null kann nicht sein!'); } else { c = a / b; } break; } document.getElementById("screen").value = c; } window.onload = function () { for (var i = 0; i < 10; i++) { (function (val) { document.getElementById("btn_" + val).onclick = function () { PutNum(val); } })(i); } document.getElementById("add").addEventListener("click", add); document.getElementById("calculate").addEventListener("click", calculate); document.getElementById("sub").addEventListener("click", sub); document.getElementById("mult").addEventListener("click", mult); document.getElementById("div").addEventListener("click", div); document.getElementById("clr").addEventListener("click", clr); } 1 -й Вопрос что делает функция: function PutNum(val) { document.getElementById("screen").value = (document.getElementById("screen").value + val)-0; Как я понимаю: велью а + атрибут велью б и минус 0. Можно ли как то проще написать или это вполне адекватно? )) В исполнении 0 получается промежуточное значение, т.е. оператор, как его заменить на само значение оператора, чтоб вместо ноля в калькуляторе отображался + - / *. Пробовал заменить, но минус считает криво. 2-й Вопрос, что делает эта функция, для чего используется цикл: window.onload = function () { for (var i = 0; i < 10; i++) { (function (val) { document.getElementById("btn_" + val).onclick = function () { PutNum(val); } })(i); } document.getElementById("add").addEventListener("click", add); document.getElementById("calculate").addEventListener("click", calculate); document.getElementById("sub").addEventListener("click", sub); document.getElementById("mult").addEventListener("click", mult); document.getElementById("div").addEventListener("click", div); document.getElementById("clr").addEventListener("click", clr); } 3 - й Вопрос, можно ли этот код допиписать с использованием методов: function Calculator() { var methods = { "+" : function(a,b) { return a + b; }, "-" : function(a,b) { return a - b; }, "*" : function(a,b) { return a * b; }, "/" : function(a,b) { return a / b; } } } Заранее очень Благодарен! |
hbsv,
Цитата:
-0 дает то, что если это будет не цифра, то возникнет ошибка. Зачем - непонятно, т. к. эта функция привязана к клавишам ввода цифр. Без -0 все точно так же работает. Цитата:
Цитата:
Ну а как вам моя последняя версия? Есть вопросы, замечания? |
Цитата:
Цитата:
Цитата:
Я рассмотрел два варианта на jQuery и Вашу работу методом обратной польской записи, и для меня это пока, что рано. Сначала надо освоить основы чистого js) Еще раз большое спасибо, ваш пример, дал мне хорошее понимание в целом ) |
Калькулятор простой
hbsv,
<!DOCTYPE HTML> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> .screen{ border: 1px solid #8B4513; width: 120px; display: inline-block; border-radius: 2px; text-align: right; } .calculator{ width: 120px; text-align: center; } .calculator input{ width: 20%; } </style> </head> <body> <form> <table class="calculator"> <tr> <td> <span class="screen" >0</span> </td> </tr> <tr> <td> <input class="button" type="button" value="1" /> <input class="button" type="button" value="2" /> <input class="button" type="button" value="3" /> <input class="button" type="button" value="+" /> </td> </tr> <tr> <td> <input class="button" type="button" value="4" /> <input class="button" type="button" value="5" /> <input class="button" type="button" value="6" /> <input class="button" type="button" value="-" /> </td> </tr> <tr> <td> <input class="button" type="button" value="7" /> <input class="button" type="button" value="8" /> <input class="button" type="button" value="9" /> <input class="button" type="button" value="*" /> </td> </tr> <tr> <td> <input class="button" type="button" value="c" /> <input class="button" type="button" value="0" /> <input class="button" type="button" value="=" /> <input class="button" type="button" value="/" /> </td> </tr> </table> </form> <script> window.addEventListener("DOMContentLoaded", function() { var calculator = document.querySelector(".calculator"), screen = document.querySelector(".screen"); var methods = { a: 0, b: 0, "+": function() { return this.a += this.b }, "-": function() { return this.a -= this.b }, "*": function() { return this.a *= this.b }, "/": function() { return this.a /= this.b }, out: function(a) { screen.innerHTML = a }, fix: function(a) { return (this[a] * 100 | 0) / 100 }, cur: 0, res: function(a) { if (a == +a) if (!this.cur) { this.a = +(this.a + "" + a); this.out(this.fix("a")) } else { this.b = +(this.b + "" + a); this.out(this.fix("a") + this.cur + this.fix("b")) } else if (a == "c") { this.b = this.a = this.cur = 0; this.out(0) } else if (this.cur) { if (!this.b && this.cur == "/") { this.out("err"); return } !this.b && this.cur != "*" && (this.b = this.a); this[this.cur](); this.out(this.fix("a")); this.b = 0; this.cur = a == "=" ? 0 : a } else if (a != "=") { this.out(this.fix("a") + a); this.cur = a } } }; calculator.addEventListener("click", function(event) { var cls = event.target.classList; if (cls && cls.contains("button")) { val = event.target.value; methods.res(val) } }) }); </script> </body> </html> |
Огромнейшее Всем спасибо за Помощь!
Все вопросы решил, кроме одного. Вопрос с нулем остался. Может есть у кого какие идеи переписать или решить? |
Часовой пояс GMT +3, время: 08:52. |