【问题标题】:How can I divide a variable multiple times in a function with Javascipt?如何使用 Javascript 在函数中多次划分变量?
【发布时间】:2021-08-28 06:37:43
【问题描述】:

我在尝试创建一个根据材料的半衰期计算材料剩余量的函数时遇到问题。

function halfLife(quantity, halfLifeTime, timeElapsed) {
    let decay = (timeElapsed / halfLifeTime);
    let remainingQuantity;

    if (decay >= 1 && decay % 1 === 0) {
        for (let i = 0; i < decay; i++) {
            remainingQuantity = quantity / 2;
        }
        return remainingQuantity;
    } else if (decay < 1) {
        let partialDecay = .5 / halfLifeTime;
        return remainingQuantity = quantity - partialDecay;
    }
}

let actual = halfLife(1, 4, 1);
let expected = .875;

if (actual === expected) {
    console.log("Test PASSED!");
} else {
    console.error("Test FAILED.");
    console.group("Result:");
    console.log("  actual:", actual);
    console.log("expected:", expected);
    console.groupEnd();
}

actual = halfLife(2, 2, 4);
expected = 1 / 2;

if (actual === expected) {
    console.log("Test PASSED!");
} else {
    console.error("Test FAILED. Keep trying!");
    console.group("Result:");
    console.log("  actual:", actual);
    console.log("expected:", expected);
    console.groupEnd();
}
  

如果一个输入必须被多次分割,第一个'if'语句只会将一个输入分割一次并返回它。我做的第一个测试工作正常,但第二个是问题。有不清楚的地方见谅,我还在学习中!

【问题讨论】:

    标签: javascript function for-loop


    【解决方案1】:

    在你的循环中,你有

    for (let i = 0; i < decay; i++) {
      remainingQuantity = quantity / 2;
    }
    

    但是由于quantity 在循环中永远不会改变,所以除法的结果总是相同的。即,您总是将原始 quantity 值除以 2。

    你可能想要类似的东西

    let remainingQuantity = quantity;
    for (let i = 0; i < decay; i++) {
      remainingQuantity = remainingQuantity / 2; 
      
      // or the short form of the above 
      // remainingQuantity /= 2;
    }
    

    请注意,a /= 2a = a / 2 的缩写形式。所以在循环中只使用两个语句中的 一个。你更喜欢哪个。

    编辑

    除了编程问题之外,计算部分衰减的方式似乎也有些偏差。

    首先,半衰期四分之一的衰变恰好是 1/8,这似乎很奇怪。这不符合放射性衰变的指数性质。预期值约为0.841

    此外,部分衰减的数量似乎与初始数量无关。因此,如果您调用halfLife(10, 4, 1),结果将是9.875。对于halfLife(100, 4, 1),它将是99.875,依此类推。这些结果显然是错误的……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 2015-08-01
      相关资源
      最近更新 更多