gpt4 book ai didi

javascript - math.round 与 parseInt

转载 作者:行者123 更新时间:2023-12-02 08:40:36 25 4
gpt4 key购买 nike

有一个简单的 JS 问题。 math.round 和 parseInt 有什么区别?

我制作了一个 JS 脚本来对提示数字的倒数求和:

    <script type="text/javascript">
var numRep = prompt("How many repetitions would you like to run?");
var sum = 0;
var count = 0;
var i = 1; //variable i becomes 1


while (i <= numRep) {// repeat 5 times

var number = prompt("Please enter a non zero integer");

if(number==0){
document.write("Invalid Input <br>");
count++;
}
else{
document.write("The inverse is: " + 1/number + "<br>");
sum = sum + (1/parseInt(number)); //add number to the sum
}

i++; //increase i by 1
}

if (sum==0){
document.write("You did not enter valid input");}
else { document.write("The sum of the inverses is: " + sum); //display sum
}
</script></body></html>

它使用parseInt。如果我想让它使用 math.round,我还需要做什么才能让它知道相应地限制小数位数?

换句话说,math.round 是否必须以某种方式格式化?

最佳答案

这两个功能确实有很大不同。

parseInt() 从字符串中提取数字,例如

parseInt('1.5')
// => 1

Math.round() 将数字四舍五入到最接近的整数:

Math.round('1.5')
// => 2

parseInt() 可以通过删除多余的文本来获取其编号,例如:

parseInt('12foo')
// => 12

但是,Math.round 不会:

Math.round('12foo')
// => NaN

您可能应该使用 parseFloatMath.round 因为您正在从用户那里获取输入:

var number = parseFloat(prompt('Enter number:'));
var rounded = Math.round(number);

关于javascript - math.round 与 parseInt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8170865/

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