猿问

如果给定的小数点四舍五入为整数,如何修改该函数以返回true,否则返回false?

我正在从事Javascript练习。我正在尝试修改一个函数,以在给定的十进制四舍五入为偶数时返回true,否则将其返回false。


到目前为止,我有


function isRoundedNumberEven(decimal){


}

console.log(isRoundedNumberEven(2.2), '<-- should be true');

console.log(isRoundedNumberEven(2.8), '<-- should be false');


蝴蝶不菲
浏览 199回答 3
3回答

BIG阳

您已经描述了两个步骤。四舍五入。这很容易实现Math.round()确定它是偶数还是奇数。确定此值的最简单方法是将其除以2,然后检查余数。如果余数为零,则数字为偶数。否则,这很奇怪。执行此操作%的方式是使用模运算符-在这种情况下,roundedNumber % 2除以2时会得到余数。您只需要检查此余数是否为0或1,并且由于您想“返回true数字是否为偶数”,那么简单的方法是return roundedNumber % 2 === 0;我已经提供了工具。现在交给您,以正确的方式组装它们。

蛊毒传说

这里需要两个关键函数:Math.round(decimal)和取模函数:“%”。第一个将舍入一个十进制值。因此,Math.round(2.2)== 2,Math.round(2.8)== 3。第二个将在整数除以数字后找到余数。因此,2%2 == 0,而3%2 == 1。因此,函数的内容应为:return&nbsp;Math.round(decimal)&nbsp;%&nbsp;2&nbsp;===&nbsp;0;

翻过高山走不出你

function isRoundedNumberEven(decimal){&nbsp; &nbsp; if((Math.round(decimal)%2) == 0) {&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; return false;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答