對于背景關系,這是我的問題:
我有一個零件表。零件是由一組材料制成的,我們稱其為常數材料變數 z。所以這張表是所有由一組材料生產的零件的表。此表中的每一行都是一個新部分。還有一串列示將由一組材料生產的零件數量。
所以如果我有:
var z = 1 //just some constant
var x = 5 //the amount of parts produced from a single set of materials
var y = 23 //the total amount of parts that have to be made
我知道一組材料生產的零件數量,也知道需要生產的零件數量。我永遠不能生產比需要少的零件,所以我知道 4 套材料可以生產 20 個零件,而我仍然會短缺 3 個零件。如果我使用 5 套材料,我可以生產 25 個零件,其余 2 個零件。
我的問題是我嘗試使用 mod 解決這個問題,但我在某處犯了錯誤
//Fun
const fun = async () => {
try {
let x = 23;
let y = 5;
const result = x/y
if(x%y == 0) {
console.log(x, ' divided by', y, ' has remainder of: ', x%y);
console.log(y, ' divided by', x, ' has remainder of: ', y%x);
}
else {
console.log(x, ' divided by', y, ' has remainder of: ', x%y);
console.log(y, ' divided by', x, ' has remainder of: ', y%x);
}
} catch (err) {
console.log(err.message);
}
}
因此,為了進一步增加清晰度,我總是想找到一個數字可以除以某物的最大次數,如果它有余數,則記錄余數。可能的解決方案是區分正數或負數余數嗎?任何幫助表示贊賞,謝謝!
uj5u.com熱心網友回復:
Math.floor( A/B ),其中 A 是所需的數字,B 是一組中的件數,將為您提供除數之前的除數(因為除法只是可以從 A 中減去 B 的次數,因此我們使用 Math.floor向下舍入),(A%B)之后會給你余數。
uj5u.com熱心網友回復:
如果你想知道 X 可以除以 Y 多少次,你可以
yz = x
z*log(y) = log(x)
z = log(x)/log(y)
根據您的問題,從這里您可以選擇 floor(z) 或 ceil(z)。
uj5u.com熱心網友回復:
這可能不是您要尋找的,但它是到達您要去的地方的一種速記方式。
const fun = (x, y) => {
let r = x % y; // store our modulus here
return !r ? [x, 0] : [(y - r x), y - r];
// if there is no remainder, return the dividend and zero: x, 0
// otherwise, the next whole number result is found by
// subtracting the modulus from the divisor and adding the dividend: (y - r x)
// and the difference between the new divisor and the old divisor is the divisor minus the modulus: (y - r)
}
我讓它在一個陣列中回傳,但你可以很容易地把它轉換成你的字串格式join(',')
const fun = (x, y) => {
let r = x % y;
return !r ? [x, 0] : [(y - r x), y - r];
}
console.log(fun(23, 5))
console.log(fun(33, 2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/449032.html
標籤:javascript 反应 分配 模数 模组
上一篇:如何僅覆寫特定通知的通知配置?
