Search code examples
c++operatorsoperations

my program prints out a different result from what expected


so every time i try to put an "n" in, the first line will put out a number that is equal to n+1. so please help me what i did wrong! thank you

#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS
#include "../../../std_lib_facilities.h"
int main()
{
cout << "Enter a number: ";
double n;
cin >> n;
cout << "n: " << n
    << "\n++n: " << ++n
    << "\nThree times of n: " << n * 3
    << "\nTwice n: " << n + n
    << "\nHalf of n: " << n / 2
    << "\nSquare root of n " << sqrt(n);
int m = n;
cout << "\nInteger of n: " << m
    << "\nRemainder when divide n by 2: " << m % 2
    << "\nDivision when divide n by 2: \n" << m / 2;
keep_window_open();
}

Solution

  • n++ changes the value of n. None of your other expressions do. That fact that you get n+1 makes it pretty clear that the n++ is being evaluated before all the other "stuff" is output (and so n is already incremented).