数学输入,计算和输出Javascript与分数/小数

Math Input, Calculate, and Output Javascript with Fractions/Decimals

本文关键字:小数 Javascript 输入 计算 输出      更新时间:2023-09-26

我想知道Javascript中的程序是否有可能接收分数作为输入并使用这些分数来计算某些值。我试图制作一个百分比差异(物理)计算器,它使用公式((|max-min|)/((最大值+最小值)/2))*100.我已经了解如何操作输入并将其拆分为数组。因此,我将最大值和最小值存储在 val1 和 val2 中。但是,问题来自计算。最初,我将整个公式集中在一个语句中,但它不起作用。因此,我将计算分成多个步骤,并在每个步骤后将值存储在变量中,以确保它正确执行计算。这是我所拥有的:

var step1=Math.abs(val1-val2);
var step2=val1+val2;
var step3=step2/2;
var step4=step1/step3;
var final=Math.round(step4*100*100)/100;

但是,计算仍然存在很多故障,尤其是分数和小数。例如,输入 90/100 和 89/100 时的百分比值与放置 9/10 和 89/100 时的百分比值相差甚远。偶尔,输入小数返回 NaN。我真的不明白发生了什么。任何能够突出上述代码在计算百分比差异方面的问题,或者教我Javascript如何计算并展示计算如何与我收到的输出保持一致的人肯定会有所帮助。

谢谢。:)

如果有任何帮助,这是程序的完整代码。如果解决问题时没有必要,则可以忽略它。我已经删除了问题中所有完全不必要的代码部分。

<html>
<head>
  <title></title>
</head>
<style type="text/css">
</style>
<script>
  var def;
  function submit() {
    var e = document.getElementById("topic");
    var ter = document.getElementById("term").value;
    var strUser = e.options[e.selectedIndex].value;
    if (!strUser) {
      document.getElementById("textcom").value = "Please specify what needs to be solved.";
    }
    else if (!term) {
      document.getElementById("textcom").value = "Please specify the values used to calculate.";
    }
    else {
      if (strUser == "a") {
        var arr = ter.split(",");
        var val1 = parseInt(arr[0]);
        var val2 = parseInt(arr[1]);
        if (arr.length > 2 || arr.length < 2) {
          def = "Error. Incorrect number of values written.";
        }
        else if (isNaN(val1) || isNaN(val2)) {
          def = "Error. One or more values input is/are not a number.";
        }
        else {
          var step1 = Math.abs(val1 - val2);
          var step2 = val1 + val2;
          var step3 = step2 / 2;
          var step4 = step1 / step3;
          var final = Math.round(step4 * 100 * 100) / 100;
          def = final + "%";
        }
      }
      document.getElementById("textcom").value = def;
    }
  }
</script>
<body>
  <h1>Physics Calculator</h1>
  <span>Please choose desired solution:</span>
  <select id="topic">
    <option disabled selected value>------ Option ------</option>
    <option value="a">Percent Difference</option>
  </select>
  <br>
  <span>Values:</span>
  <input type="text" id="term"></input>
  <br>
  <br>
  <textarea rows="20" cols="40" id="textcom">Uneditable. For output purposes only.</textarea>
  <br>
  <button onclick="submit()">Submit</button>
  <script>
    document.getElementById("textcom").readOnly = "true";
  </script>
</body>
</html>
似乎

您希望 JavaScript 在对它们应用parseInt时将像 12/100 这样的分数识别为数值。

事实并非如此,因为:

  • 除法(/)是JavaScript(和大多数其他语言)中的运算符,而不是数字符号(如十进制.)。数字文字中不允许使用像 / 这样的字符。
  • 即使你输入数字作为小数(如15.89),函数parseInt也会忽略小数部分——parseInt的名字已经揭示了这种行为。您应该使用 parseFloat 或更短的 将单一+应用于字符串,这会将其隐式转换为数字。

为了解决这个问题,你可以编写一个函数,将分数符号转换为它们所代表的数字。我在下面的代码片段中调用了该函数 evaluate

// To interpret fractions (with '/') as numbers:
function evaluate(term) {
  // remove spaces and get numerator and denominator
  var arr = term.replace(/ /g, '').split('/');
  // get part before '/' and turn into number
  var val = +arr.shift();
  // read denominator(s) and perform division(s)
  while (arr.length) { 
    val = val / +arr.shift();
  }
  return val;
}
function submit() {
  var e = document.getElementById("topic");
  var ter = document.getElementById("term").value;
  var strUser = e.options[e.selectedIndex].value;
  var def;
  if (!strUser) {
    def = "Please specify what needs to be solved.";
  }
  else if (!term) {
    def = "Please specify the values used to calculate.";
  }
  else if (strUser == "a") {
    var arr = ter.split(",");
    var val1 = evaluate(arr[0]);
    var val2 = evaluate(arr[1]);
    if (arr.length !== 2) {
      def = "Error. Incorrect number of comma-separated values written; two expected.";
    }
    else if (isNaN(val1) || isNaN(val2)) {
      def = "Error. One or more values input is/are not a number.";
    }
    else {
      var step1 = Math.abs(val1 - val2);
      var step2 = val1 + val2;
      var step3 = step2 / 2;
      var step4 = step1 / step3;
      var final = Math.round(step4 * 100 * 100) / 100;
      def = final + "%";
    }
  }
  document.getElementById("textcom").value = def;
}
<span>Please choose desired solution:</span>
<select id="topic">
  <option disabled selected value>------ Option ------</option>
  <option value="a" selected>Percent Difference</option>
</select>
<br>
<span>Values:</span>
<input type="text" id="term"></input>
<br>
<br>
<textarea readonly rows="3" cols="40" id="textcom">Uneditable. For output purposes only.</textarea>
<br>
<button onclick="submit()">Submit</button>

注意:请注意,您可以在 HTML 中使用 readonly 属性 - 无需通过 JavaScript 进行设置。