JavaScript Math - 得到错误的答案(128 - 64 = -64)?

时间:2016-04-05 18:24:05

标签: javascript jquery math

我正在尝试为显卡制作一个低级别的性能比较工具,除了总线宽度比较之外,我还能正常工作。



var bl_bus = $('#baseline-ram-bus-width').val();
var tg_bus = $('#target-ram-bus-width').val();

// Memory Bus Width
    if (tg_bus < bl_bus) {
        $('#compare-bus-bl span').text("+" + (bl_bus - tg_bus));
        $('#compare-bus-tg span').text((tg_bus - bl_bus));
    }
    if (tg_bus === bl_bus) {
        $('#compare-bus-bl span').text("Equal");
        $('#compare-bus-tg span').text("Equal");
    }
    if (tg_bus > bl_bus) {
        $('#compare-bus-bl span').text((tg_bus - bl_bus));
        $('#compare-bus-tg span').text("+" + (bl_bus - tg_bus));
    }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label for="baseline-ram-bus-width">Baseline Memory Bus Width:</label>
<input id="baseline-ram-bus-width" type="number" placeholder="Memory Bus Width (b)" value="128"> bits
<br>

<label for="target-ram-bus-width">Target Memory Bus Width:</label>
<input id="target-ram-bus-width" type="number" placeholder="Memory Bus Width (b)" value="64"> bits
<br><br>

<table>
    <tr>
        <th>Memory Bus Width</th>
        <td id="compare-bus-bl"><span>0</span> bits</td>
        <td id="compare-bus-tg"><span>0</span> bits</td>
    </tr>
</table>
&#13;
&#13;
&#13;

据我所知,我已正确编码。在我的示例中,基线是128位,目标是64位,应该使用第一个if语句,因为目标总线宽度小于基线。

然而,结果与我的预期完全不同。出于某种原因,JavaScript似乎认为答案是基线为-64位,目标为+64位。

我花了几天时间试图弄清楚为什么会发生这种情况,甚至要重新编码整个文件,但结果却出现了同样的错误。有人可以对此有所了解吗?我感觉有一些明显的东西,我没有注意到。

2 个答案:

答案 0 :(得分:3)

确保以整数格式(正如我更正)获取值

var bl_bus = +$('#baseline-ram-bus-width').val();
var tg_bus = +$('#target-ram-bus-width').val();

答案 1 :(得分:3)

我在做任何数学之前解析了这些值。这看起来是对的吗?

var bl_bus = parseInt( $('#baseline-ram-bus-width').val(), 10);
var tg_bus = parseInt( $('#target-ram-bus-width').val(), 10);

// Memory Bus Width
    if (tg_bus < bl_bus) {
        $('#compare-bus-bl span').text("+" + (bl_bus - tg_bus));
        $('#compare-bus-tg span').text((tg_bus - bl_bus));
    }
    if (tg_bus === bl_bus) {
        $('#compare-bus-bl span').text("Equal");
        $('#compare-bus-tg span').text("Equal");
    }
    if (tg_bus > bl_bus) {
        $('#compare-bus-bl span').text((tg_bus - bl_bus));
        $('#compare-bus-tg span').text("+" + (bl_bus - tg_bus));
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label for="baseline-ram-bus-width">Baseline Memory Bus Width:</label>
<input id="baseline-ram-bus-width" type="number" placeholder="Memory Bus Width (b)" value="128"> bits
<br>

<label for="target-ram-bus-width">Target Memory Bus Width:</label>
<input id="target-ram-bus-width" type="number" placeholder="Memory Bus Width (b)" value="64"> bits
<br><br>

<table>
    <tr>
        <th>Memory Bus Width</th>
        <td id="compare-bus-bl"><span>0</span> bits</td>
        <td id="compare-bus-tg"><span>0</span> bits</td>
    </tr>
</table>