Simple math in C++: Difference between revisions
No edit summary |
|||
| Line 34: | Line 34: | ||
</pre></code> | </pre></code> | ||
C++ will perform operations via BEDMAS (or | C++ will perform operations via BEDMAS (or PEMDAS, or however you learned it in middle school). That means brackets (or parantheses) will be computed first. Then exponents, then division and multiplication, and then finally addition and subtraction. The above code will take the number six, and then convert it to a floating point number. Then it will multiply 6 by pi, which will return a floating point number. Then twelve, which has been converted to a float, will be added to the result. So myResult at this point will contain 30.84. Then five will be converted to a float and subtracted from myResult. The result will be 25.84. | ||
This should be pretty straightforward. Now, take a look at the last line of the above code. Notice that we are taking the variable and adding another value to it, and then dumping it back into itself. You've just had to type the same variable name twice in a row, which could lead to typos, and also takes up time. There is an easier way to do this! Each of the following lines has an equivalent line of code that follows. | This should be pretty straightforward. Now, take a look at the last line of the above code. Notice that we are taking the variable and adding another value to it, and then dumping it back into itself. You've just had to type the same variable name twice in a row, which could lead to typos, and also takes up time. There is an easier way to do this! Each of the following lines has an equivalent line of code that follows. | ||