简体   繁体   中英

How to write order of operations in javascript

I am doing a class project and I am stuck on how to code the order of operations. The instructor has given us this information:

    <table class="table">
    <tr>
        <td class="subTitle" colspan="7">
            Order of Operations
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="ooo1" value="12">
        </td>
        <td>
            <input type="text" id="ooo2" value="22">
        </td>
        <td>
            <input type="text" id="ooo3" value="378">
        </td>
        <td>
            <input type="text" id="ooo4" value="45">
        </td>
        <td>
            <input type="text" id="ooo5" value="2">
        </td>
        <td>
            =
        </td>
        <td>
            <div id="oooResult">000000000</div>
        </td>
    </tr>
    <tr>
        <td colspan="7" class="buttonTD">
            <input type="button" value="Add First & Third, Subtract   
            Fifth, 
            Multiply by Second, then Divide by Fourth" onclick="">
        </td>
    </tr>   

In an external java script file I am supposed to program so that when I open the HTML page and click the button, the answer will appear. He wants us to Add the first and third number, subtract the fifth, multiply by the second and divide by the fourth.

Here is my external java script file with the addition and subtraction portion of this project.

    function Add()
    {
      var firstNum = document.getElementById('add1').value;
      var secondNum = document.getElementById('add2').value;
      var total = parseInt(firstNum) + parseInt(secondNum);
      document.getElementById('addResult').innerHTML = total;
    }
    function Subtract()
    {
      var firstNum = document.getElementById('sub1').value;
      var secondNum = document.getElementById('sub2').value
      var total = parseInt(firstNum) - parseInt(secondNum);
      document.getElementById('subResult').innerHTML = total;
    }

I just need help getting started with the order of operations so that I can finish it. I just do not know where to begin.

Some hints:

  • You forgot to pass the second parameter to parseInt
  • Don't use the DOM to store the intermediate values. Return them from the functions.
  • So first read the inputs, then do all the calculations (as @bfavaretto suggested), then do the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM