Search code examples
c++mathexpressionalgebraarithmetic-expressions

How Do I Translate This Algebraic Expression In C++?


I need to write and execute a program in C++ that computes the value of the expression:

5x^2 + 12y / 3x , Where x = 12, And y = 9.8

This is what I have:

int num1 = 12; float num2 = 9.8; float totalResult;
totalResult = 5 * num1 * num2 + 12 * num2 / 3 * num1;

cout << totalResult;

The answer is 23.2667 but I'm getting a wrong result.


Solution

  • Your issue is order of operations (and a typo on num1 * num2).

    Your proposed correct answer is 23.2667, which is only possible if you interpret / as being the last operation. To force the division to happen last, put the left and right sides in parentheses:

    totalResult = (5 * num1 * num1 + 12 * num2) / (3 * num1);
    

    That way it executes in this order:

                     1      2      4    3       6    5
    totalResult = (5 * num1 * num1 + 12 * num2) / (3 * num1);
    

    Otherwise, it was executing in this order:

                    1      2      6    3      4   5
    totalResult = 5 * num1 * num1 + 12 * num2 / 3 * num1;
    

    Here's a proof with JavaScript:

    var num1 = 12; var num2 = 9.8; 
    var totalResult = (5 * num1 * num1 + 12 * num2) / (3 * num1);
    console.log(totalResult);

    Operator Precedence Reference