请仅使用JavaScript。
这是我第一次尝试自行编写JavaScript。我已经成功地操纵了朋友过去为我编写的代码,但是直到最近,我才从头开始编写自己的代码,也从未花时间去尝试和理解语言本身。
我正在尝试制作一个基本的文胸尺寸计算器,该计算器从用户输入中获取数字(度量值),将其路由到一个函数中,然后向用户返回(计算)文胸尺寸。
由于我是该语言的新手,所以我现在只想写一部分-“ band size”
I have an input field for users to type in their "under bust measurement" which I currently have set to round. This works as it intended. See here
<html>
<head>
<script type="text/javascript">
function calculate()
{
var underbust = document.getElementById("underBust").value;
if (underbust.length === 0)
{
alert("Please enter your underbust measurement in inches");
return;
}
document.getElementById("bandsize").innerHTML = Math.round(underbust);
}
</script>
</head>
<body>
<input type="number" id="underBust" /> inches<br>
<input type="submit" value="Submit" onclick="calculate()" /><br>
<b>underbust:</b> <div id="bandsize">bandsize will appear here</div><br>
</body>
</html>
However, I don't need the input 'underBust' to round to the nearest whole number. I need it to round to the nearest EVEN whole number, since bra band sizes only come in even whole numbers.
For example, if the user inputs the number "31.25" the code would currently round it to "31" but I need it to round it to "32"
If the user inputs the number "30.25" the code would round it correctly to "30" because the nearest whole number and nearest whole even number are the same in this case. However, if the user inputs "30.5" the code would round it up to "31" but I still need it to round down to "30"
基本上,如果用户输入等于或大于一个奇数(29.00变为30,31.25变为32,依此类推),则需要四舍五入该数字。如果用户输入大于或等于偶数且小于下一个奇数(28、28.25、28.75等),则需要四舍五入(在前面的示例中,所有情况下均为28)。奇数是四舍五入的中间除法,而不是任何数字的“ .5”。
这可能吗?
应该这样做:
2 * Math.round(underbust / 2);
谢谢!我觉得这是一些我应该知道的基本数学,但是没有考虑……是的。只是做数学而已,我现在觉得很愚蠢。
我可以给您一个数学上的解释,但您可能可以通过脑海中带有示例值的表达式来更好地理解它。
那么最近的ODD为:2 * Math.floor(n / 2)+ 1
@Nitin否,
Math.ceil(0.1)
四舍五入为1(奇数),而不是0(偶数)@Henrik,我认为Nitin指的是Math.ceil(),
2 * Math.ceil(0.1 / 2)
因为它将给出2-下一个偶数整数。