我正在努力制定一个 Javascript 函数,该函数允许我根据 2 条规则从用户输入中创建 2 个数字。
let userInput;
let num1;
let num2;
规则:num1 + num2 = userInput 和 num1 - num2 必须是可能的最小正数。
因此,用户输入 5 时,函数应该为 num1 和 num2 返回 3 和 2,而不是 4 和 1。
你能帮我制定这样一个Javascript函数吗?
在此先感谢您的帮助 :)
我正在努力制定一个 Javascript 函数,该函数允许我根据 2 条规则从用户输入中创建 2 个数字。
let userInput;
let num1;
let num2;
规则:num1 + num2 = userInput 和 num1 - num2 必须是可能的最小正数。
因此,用户输入 5 时,函数应该为 num1 和 num2 返回 3 和 2,而不是 4 和 1。
你能帮我制定这样一个Javascript函数吗?
在此先感谢您的帮助 :)
回复时没有收到通知。有很多方法可以解决这个问题,但我会使用Math.ceil()
,它会自动四舍五入任何小数,然后向下舍入Math.floor()
。
let userInput = 5;
let num1 = Math.ceil(userInput/2);
let num2 = Math.floor(userInput/2);
console.log(userInput, num1, num2)
另一种方法可能是除以userInput
2 并用于parseInt()
截断所有小数,然后添加userInput%2
到该结果,如果userInput
是奇数则为 1,如果为偶数则为 0。减去num1
得到。userInput
_num2
let userInput = 5;
let remainder = userInput%2 // 1
let num1 = parseInt(userInput/2) + remainder;
let num2 = userInput - num1;
console.log(userInput, num1, num2)