gpt4 book ai didi

java - 计算器无法正常计算三位数

转载 作者:行者123 更新时间:2023-12-01 06:57:37 27 4
gpt4 key购买 nike

所以我的计算器可以完美地处理任何涉及两位数字(包括 C 按钮)的计算,但是如果我尝试任何三位数计算,这实际上不起作用,例如 1 + 2 + 3 = 5 有人可以告诉我为什么会这样,无论如何我可以修复它吗?

public class Calculator {  

private long currentInput; //current input
private long previousInput; // previous input
private long result; // result of calculation
private String lastOperator = ""; // keeps track of the last operator entered


/* New digit entered as integer value i - moves currentInput 1 decimal place to the left and adds i in "one's column" */
public void inDigit(long i) {
currentInput = (currentInput * 10) + i;
}


/* Operator entered + - or * */
public void inOperator(String op) {
previousInput = currentInput; // save the new input as previous to get ready for next input
currentInput = 0;
lastOperator = op; // remember which operator was entered
}


/* Equals operation sets result to previousInput + - or * currentInput (depending on lastOperator) */
public void inEquals() {
if (lastOperator.equals("+")) {
result = previousInput + currentInput;
} else if (lastOperator.equals("-")) {
result = previousInput - currentInput;
} else if (lastOperator.equals("*")) {
result = previousInput * currentInput;
}
lastOperator = ""; // reset last operator to "nothing"
}


/* Clear operation */
public void inClear() {
currentInput = 0;
previousInput = 0;
result = 0;
lastOperator = "";
}

/* returns the current result */
public String getResult() {
return Long.toString(result); //converts int to String
}

/* returns the previous input value */
public String getPreviousInput() {
return Long.toString(previousInput);
}
/* returns the current input value */
public String getCurrentInput() {
return Long.toString(currentInput);
}

最佳答案

好吧,您只存储最后两个操作数,因此对于 1 + 2 + 3 = 5 的示例,当您输入第二个 + 符号时,1 会丢失,而 2 + 3 = 5。

关于java - 计算器无法正常计算三位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7747003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com