[英]JS calculator bug
PS new to js, I made an ios like calculator in js in which the basic functioning is the user enters the first number which gets stored in a variable , screen gets cleared then the user enters the second number which again needs to be stored in a variable. PS 新来的 js,我在 js 中制作了一个类似 ios 的计算器,其中基本功能是用户输入存储在变量中的第一个数字,屏幕被清除,然后用户输入第二个数字,该数字再次需要存储在一个多变的。 I am currently having problem in storing the second number.我目前在存储第二个数字时遇到问题。
const getnum = () => {
let firstnum = parseFloat(ans.innerText);
console.log("firstnum" + "=" + firstnum);
};
Copied this from internet to get the second number从互联网上复制这个以获得第二个数字
operationperf = (operation) => {
if (!numinmem) {
numinmem = parseFloat(ans.textContent);
operatorinmem = operation;
ans.textContent = "";
return;
}
operatorinmem = operation;
ans.textContent = getResultOfOperationAsStr();
ans.textContent = "";
};
but this causes both the variables to have the same value so if i do 50+78 the calculator performs 50+50但这会导致两个变量具有相同的值,因此如果我执行 50+78 计算器执行 50+50
working demo: https://megahedron69.github.io/ios-Calculator/ javascript file:https://github.com/Megahedron69/ios-Calculator/blob/main/app.js工作演示: https : //megahedron69.github.io/ios-Calculator/ javascript 文件:https ://github.com/Megahedron69/ios-Calculator/blob/main/app.js
First of all, it seems that your numinmem
variable is not being used outside the scope of operationperf
function for any further processing.首先,您的numinmem
变量似乎没有在operationperf
函数的范围之外用于任何进一步处理。
Also, in your following function:此外,在您的以下功能中:
const getResultOfOperationAsStr = () => {
const currentValueNum = parseFloat(ans.textContent);
const valueNumInMemory = parseFloat(ans.textContent);
let newValueNum;
if (operatorinmem === "addition") {
newValueNum = valueNumInMemory + currentValueNum;
} else if (operatorinmem === "subtraction") {
newValueNum = valueNumInMemory - currentValueNum;
} else if (operatorinmem === "multiplication") {
newValueNum = valueNumInMemory * currentValueNum;
} else if (operatorinmem === "division") {
newValueNum = valueNumInMemory / currentValueNum;
}
return newValueNum.toString();
};
It appears that your are using the current value of the element stored in ans
variable for both sides of your operations (eg ansValueAsFloat + ansValueAsFloat
), hence, producing the undesired behavior.您似乎在操作的双方都使用ans
变量中存储的元素的当前值(例如ansValueAsFloat + ansValueAsFloat
),因此会产生不希望的行为。
My recommendation would be to set any of the variables involved in the final operation to the value of numinmem
and set the other to the current value in ans
.我的建议是将最终操作中涉及的任何变量设置为numinmem
的值, numinmem
设置为ans
的当前值。
Hope I made myself clear.希望我说清楚了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.