我做了一个可以在Pi上测验您的功能。对于正确书写的每个数字,您将获得一半的分数。但是,即使我只是键入“ 3”,也会说我做错了。请帮忙。
function pi() {
var piWithoutDecimals = 31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679;
var yourAnswer = prompt("Pi Bonus! Half of a point for every digit of pi that you can write from memory!");
var yourAnswerNum = parseInt(yourAnswer);
var yourAnswerMultiplier = yourAnswerNum.toString().split(".");
var yourAdjustedAnswer = yourAnswerNum*(10**parseInt(yourAnswerMultiplier));
var yourAdjustedAnswerCount = yourAdjustedAnswer.toString().length;
var yourSectionOfpiWithoutDecimals = piWithoutDecimals.toString().substring(0,parseInt(yourAdjustedAnswer-1));
if(yourSectionOfpiWithoutDecimals==yourAnswerNum) {
alert("Nice!! You listed "+yourAdjustedAnswerCount+" digits of Pi, and so you get "+Math.floor((yourAdjustedAnswerCount)/2)+" points!")
points+=Math.floor((yourAdjustedAnswerCount)/2);
} else { alert("Good try, but you got one or more digits incorrect.") }
}
pi()
答案 0 :(得分:0)
您首先在此行出错:
var yourAnswerMultiplier = yourAnswerNum.toString().split(".");
如果您将此值记录为例如输入"314"
,您将获得数组["314"]
(您可能需要.split("")
)。从那里开始,yourAdjustedAnswer
将为无穷大(因为10 ** 314太大,只会溢出)。失败了,这显然不是您想要的。
建议,尝试使用浏览器/ IDE的开发人员工具逐步执行一个简单示例,并仔细观察每个步骤是否符合您的期望。
@Orkhan Alikhanov的回答也可能提供一些提示。
function pi() {
var piWithoutDecimals = 31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679;
var yourAnswer = prompt("Pi Bonus! Half of a point for every digit of pi that you can write from memory!");
var yourAnswerNum = parseInt(yourAnswer);
var yourAnswerMultiplier = yourAnswerNum.toString().split(".");
var yourAdjustedAnswer = yourAnswerNum*(10**parseInt(yourAnswerMultiplier));
console.log(yourAdjustedAnswer)
var yourAdjustedAnswerCount = yourAdjustedAnswer.toString().length;
var yourSectionOfpiWithoutDecimals = piWithoutDecimals.toString().substring(0,parseInt(yourAdjustedAnswer-1));
if(yourSectionOfpiWithoutDecimals==yourAnswerNum) {
alert("Nice!! You listed "+yourAdjustedAnswerCount+" digits of Pi, and so you get "+Math.floor((yourAdjustedAnswerCount)/2)+" points!")
points+=Math.floor((yourAdjustedAnswerCount)/2);
} else { alert("Good try, but you got one or more digits incorrect.") }
}
pi()
答案 1 :(得分:-1)
您可能有一个简单的方法。
.
,并计数长度以获取正确输入的位数。
function pi() {
const pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";
const yourAnswer = prompt("Pi Bonus! Half of a point for every digit of pi that you can write from memory!");
if(pi.startsWith(yourAnswer)) {
const yourAdjustedAnswerCount = yourAnswer.replace('.', '').length;
alert(`Nice!! You listed ${yourAdjustedAnswerCount} digits of Pi, and so you get ${Math.floor(yourAdjustedAnswerCount / 2)} points!`)
} else {
alert("Good try, but you got one or more digits incorrect.")
}
}
pi()