首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从头开始构建JavaScript计算器?

从头开始构建JavaScript计算器?
EN

Stack Overflow用户
提问于 2018-10-06 05:45:19
回答 1查看 281关注 0票数 3

我正在尝试从头开始构建一个JavaScript计算器,而不是按照教程进行操作,作为学习练习。大部分功能都在工作,除非计算是在另一个计算之后执行的。例如:7x6+ 42在这种情况下,它将显示重置为0,但似乎无论如何都会保留变量。

是否有必要将数字存储在3个值中,而不是2个值中?目前我使用的是:-currentValue,,它保存了之前计算的总数。-newValue,用户当前正在输入的数字。

代码语言:javascript
复制
function newNum(pressed) { //Adds digit of key pressed to new number being entered.
  //console.log ("Button pressed " + pressed);

  if (newValue == 0) { //If new calculation, newValue is set to key pressed.
    newValue += pressed;
  } else { //Else if continuing calculation, key pressed is added to end of newValue.
    newValue = newValue.toString();
    newValue = newValue + pressed; //Adds digit at end of String, then converts back to Number.
    newValue = parseFloat(newValue);
  }
  document.getElementById('result').innerHTML = newValue;
}

function newCalc(pressed) { //Will use this mathematical operation to find the value.
  if (!currentValue) {
    currentValue = newValue;
  } else {
    document.getElementById('result').innerHTML = newValue;
  }

  newOperation = pressed;
  newValue = 0;
}

function equals() { //Resolves calculation.
  newValue = parseFloat(newValue);

  switch(newOperation) {
    case "/":
        currentValue = (currentValue / newValue);
        break;
    case "*":
        currentValue = (currentValue * newValue);
        break;
    case "-":
        currentValue = (currentValue - newValue);
        break;
    case "+":
        currentValue = (currentValue + newValue);
        break;
  }

  currentValue = parseFloat(currentValue);
  newValue = 0;
  document.getElementById('result').innerHTML = currentValue;
}

https://codepen.io/adam_weiler/pen/aRNppX

我还在学习,我知道代码有点臃肿。任何关于如何简化它的建议也会很有帮助!

编辑:我举了一个不好的例子。我只是在编写一个基本的计算器,你可以点击按钮来输入数字。它不使用BEDMAS;操作的顺序是“用户输入它们的顺序”。所以,是的,只是一个基本的轻击计算器。

EN

回答 1

Stack Overflow用户

发布于 2018-10-06 05:51:57

在你的例子中,代码试图同时计算7*6和6+42,但是没有6可以加到42上,因为它是乘以7的,所以不能用来计算。你应该根据操作偏好制定规则,当有乘法或除法时,应将排序数字计算为新数字,然后再进行加法或减法操作。此外,您还应该定义从左到右的规则,这样如果您有2*3/4,那么错误就不会再次发生。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52673639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档