【问题标题】:I cannot produce an error message with division when dividing by 0 (Javascript Calculator)除以 0 时,我无法生成除法错误消息(Javascript 计算器)
【发布时间】:2020-07-08 07:12:57
【问题描述】:

作为序言,我是一个尝试用 Javascript 创建计算器的初学者。我目前有一个包含数学运算符的 switch 语句。我的问题是,在 switch 语句中,我想在尝试除以 0 时包含一个涉及除法的错误消息(字符串);但是,无论我做什么,我总是在计算器的“显示”中得到无穷大。

非常感谢任何数量的帮助,即使这意味着我必须重新做这整件事。这是执行实际计算的函数的 sn-p(虽然它在一个类中,但如果需要,我将在整个代码块中进行编辑)。

selectedOperation(operation) {
        if (this.currentDisplay === '') return;
        if (this.prevDisplay !== '') {
            this.calculate();
        }
        this.operation = operation;
        this.prevDisplay = this.currentDisplay;
        this.currentDisplay = '';
}

calculate() {
        let calculation;
        const previousNum = parseFloat(this.prevDisplay);
        const currentNum = parseFloat(this.currentDisplay);
        if (isNaN(previousNum) || isNaN(currentNum)) return;
        
        switch (this.operation) {
            case '+' : 
            calculation = previousNum + currentNum
            break;
        case '-' : 
            calculation = previousNum - currentNum
            break;
        case 'x' : 
            calculation = previousNum * currentNum
            break;
        case '÷' : 
            calculation = previousNum / currentNum
            if (currentNum === 0) return "error";
            break;
        default:
            return;
        }

        this.currentDisplay = calculation;
        this.operation = undefined;
        this.prevDisplay = '';
}

**EDIT**:

getDisplayNumber(number) {
        const stringNumber = number.toString();
        const integerDigits = parseFloat(stringNumber.split('.')[0]);
        const decimalDigits = stringNumber.split('.')[1];
        let integerDisplay
        if (isNaN(integerDigits)) {
            integerDisplay = '';
        } else {
            integerDisplay = integerDigits.toLocaleString('en', {maximumFractionDigits: 0 });
        }
        if (decimalDigits != null) {
            return `${integerDisplay}.${decimalDigits}`;
        } return integerDisplay;
    }

updateDisplay() {
        this.cdisplay.innerText = 
        this.getDisplayNumber(this.currentDisplay);
        if(this.operation != null) {
            this.display.innerText = 
                `${this.prevDisplay} ${this.operation}`;

        } else {
            this.display.innerText = '';
        }
    }

【问题讨论】:

  • 您应该考虑在尝试操作之前验证currentNum。也许这个先前的答案会有所帮助:stackoverflow.com/questions/8072323/…
  • 您似乎并没有捕捉到回报,而是在selectedOperation() 中调用calculate()。将返回值存储在变量中并检查它(?)。

标签: javascript if-statement switch-statement divide-by-zero


【解决方案1】:

这是更新的解决方案。查看 cmets 中的说明。

顺便说一句,传递给addEvenListener 回调的第一个参数是event,不是按钮本身,但您可以使用event.target 访问按钮。

class Calculator {
  constructor(display, cdisplay) {
    this.display = display;
    this.cdisplay = cdisplay;
    this.clear();
  }

  clear() {
    this.currentDisplay = "";
    this.prevDisplay = "";
    // new property error
    this.error = "";
    this.operation = undefined;
  }

  del() {
    this.currentDisplay = this.currentDisplay.toString().slice(0, -1);
  }

  appendNumber(number) {
    // if an error exists and the user try to start a new operation
    // clear everything
    if (this.error) {
      this.clear();
    }
    if (number === "." && this.currentDisplay.includes(".")) return;
    this.currentDisplay = this.currentDisplay.toString() + number.toString();
  }

  selectedOperation(operation) {
    if (this.currentDisplay === "") return;
    if (this.prevDisplay !== "") {
      this.calculate();
    }
    this.operation = operation;
    this.prevDisplay = this.currentDisplay;
    this.currentDisplay = "";
  }

  calculate() {
    let calculation;
    const previousNum = parseFloat(this.prevDisplay);
    const currentNum = parseFloat(this.currentDisplay);
    if (isNaN(previousNum) || isNaN(currentNum)) return;

    switch (this.operation) {
      case "+":
        calculation = previousNum + currentNum;
        break;
      case "-":
        calculation = previousNum - currentNum;
        break;
      case "x":
        calculation = previousNum * currentNum;
        break;
      case "÷":
        // if the user divide by 0 set this.error
        if (currentNum === 0) this.error = "Can't divide by zero";
        // else calculate normally
        else calculation = previousNum / currentNum;
        break;
      default:
        return;
    }

    this.currentDisplay = calculation;
    this.operation = undefined;
    this.prevDisplay = "";
  }

  getDisplayNumber(number) {
    const stringNumber = number.toString();
    const integerDigits = parseFloat(stringNumber.split(".")[0]);
    const decimalDigits = stringNumber.split(".")[1];
    let integerDisplay;
    if (isNaN(integerDigits)) {
      integerDisplay = "";
    } else {
      integerDisplay = integerDigits.toLocaleString("en", {
        maximumFractionDigits: 0
      });
    }
    if (decimalDigits != null) {
      return `${integerDisplay}.${decimalDigits}`;
    }
    return integerDisplay;
  }

  updateDisplay() {
    // if there is an error display the error and return
    if (this.error) {
      this.display.innerText = this.error;
      return;
    }
    this.cdisplay.innerText = this.getDisplayNumber(this.currentDisplay);
    if (this.operation != null) {
      this.display.innerText = `${this.prevDisplay} ${this.operation}`;
    } else {
      this.display.innerText = "";
    }
  }
}

const cdisplay = document.querySelector("#cdisplay");
const display = document.querySelector("#display");
const numberButtons = document.querySelectorAll(".numbers");
const operationButtons = document.querySelectorAll(".operation");
const equalsButton = document.querySelector("#equals");
const delButton = document.querySelector("#del");
const clearButton = document.querySelector("#clear");
const negButton = document.querySelector("#neg");

const calculator = new Calculator(display, cdisplay);

numberButtons.forEach(button => {
  button.addEventListener("click", () => {
    calculator.appendNumber(button.innerText);
    calculator.updateDisplay();
  });
});

operationButtons.forEach(button => {
  button.addEventListener("click", () => {
    calculator.selectedOperation(button.innerText);
    calculator.updateDisplay();
  });
});

// this agrument passed to the callback function is an event not button
equalsButton.addEventListener("click", event => {
  calculator.calculate();
  calculator.updateDisplay();
});
// this agrument passed to the callback function is an event not button
clearButton.addEventListener("click", event => {
  calculator.clear();
  calculator.updateDisplay();
});
// this agrument passed to the callback function is an event not button
delButton.addEventListener("click", event => {
  calculator.del();
  calculator.updateDisplay();
});

【讨论】:

  • 感谢您的帮助!我真的很感激,您提供的解决方案确实提供了错误消息;但是,显示功能似乎发生了奇怪的交互。只有在我选择另一个运算符后才会显示错误消息。在计算器“屏幕”上,它会显示:“不能除以零+”,例如,如果我选择“+”,它对所有其他运算符也是如此。如果你想看的话,我已经在上面添加了显示功能。
  • 你能把你所有的代码贴出来或者用 Codepen 或者其他的东西分享一下,这样我就可以更好地帮助你了。
  • 是的,当然,这是链接:codepen.io/superboy20/pen/eYJrVLN
猜你喜欢
  • 2018-05-11
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
相关资源
最近更新 更多