Notification texts go here Contact Us Buy Now!

Output of Code is 114 I can't figure out why

It is the order of math operations. C++ follows the standard math operations that you would see in math.

total = two + one / total;

should be..

total = (two + one) / total;

First, let's consider the calculation of the program:

  1. When i is 0, the program runs the else section, one * two equals to 112, so total is increased by 112, and now it's 0 + 112 = 112.
  2. When i is 1, the program runs the if section, two + one / total is 2 + 56 / 112. First, notice that operator/ is prior than operator+, so it will be first calculated. Second, if the two numbers of the / calculation is both integers, the fractional part would be abandoned, so the result of 56 / 112 is 0. Then, the result of 2 + 56 / 112 is 2 + 0, and that's 2, so the value of total is now 2.
  3. When i is 2, the program runs the else section, one * two equals to 112, so total is increased by 112, because it was 2 before the addition, it should be 2 + 112 = 114 now.

In an conclusion, the key point is that because it was 2 before the addition, it should be 2 + 112 = 114 now, and don't forget that if you use operator+=, the program increases the variable by the value after the operater, but not just setting the variable to the value after the operator.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.