情境
我有房间预订表。
以下所有字段均为整数roomsneeded
(需要的总房间..根据最大访客计算)maxguest
(每间客房最多可容纳一位客人)checkin_guest_count
(需要房间的总人数)
因此,作为maxguest increases/decreases
我需要increase/decrease
roomsneeded
。
因此,请牢记以上内容,使example
假设maxguest=3
和checkin_guest_count=17
..那么我该如何计算roomsneeded
?modulus
在这里有用吗,因为我不在寻找exact divisibles
?
我正在尝试在javascript
上实现这一目标(但正在寻找基本
关于所需数学的想法)
最佳答案
只需检查Math.ceil()
,而不是检查数字是否完全可分-假设您的房间内的人数少于最大人数。
var roomsNeeded = Math.ceil( checkin_guest_count / maxguest );
// 17 / 3 => 5.6...
// Math.ceil( 17 / 3 ) => 6
下面的概念证明:
function calculate() {
// retrieving the various values required for the
// calculation:
var checkin_guest_count = document.getElementById('checkin_guest_count').value,
maxguest = document.getElementById('maxguest').value,
result = document.getElementById('result'),
// dividing the number of guests by the maximum
// number of guests per room, and then rounding
// that value up to the nearest integer (eg
// Math.ceil(5.1) will return 6):
numRooms = Math.ceil(checkin_guest_count / maxguest);
// here we update the value of the 'result' node
// to either the numRooms value (if numRooms is a
// finite number, so we haven't tried to divide by
// zero) or to 0 if the numRooms is infinite:
result.value = Number.isFinite(numRooms) ? numRooms : 0;
return numRooms;
}
// retrieving the collection of <input> elements whose
// type attribute is 'number', and converting that collection
// to an Array (using Array.from()):
var inputs = Array.from(document.querySelectorAll('input[type = number]'));
// iterating over the Array using Array.prototype.forEach():
inputs.forEach(function(input) {
// binding the named function calcuate() (note the lack of
// parentheses in the event-binding) as the event-handler
// for the 'change' event:
input.addEventListener('change', calculate);
});
label {
display: block;
margin: 0 0 0.2em 0;
}
label span {
display: inline-block;
width: 50%;
text-align: right;
}
label span::after {
content: ': ';
}
label span + input {
width: 20%;
}
<label><span>Number of guests</span>
<input type="number" id="checkin_guest_count" step="1" />
</label>
<label><span>Maximum guests per room</span>
<input type="number" id="maxguest" step="1" min="1" />
</label>
<label><span>Number of rooms</span>
<input type="number" id="result" readonly />
</label>
参考文献:
Array.from()
。Array.prototype.forEach()
。document.querySelectorAll()
。Math.ceil()
。Number.isFinite()
。