“a++”与“++a”

a++是先把a加一然后再运算

#include<iostream>
using namespace std;
int main()

{
    int a = 2, b1= 4,b2=4;
    int sum1,sum2;
    sum1 = a + (b1++);
    sum2 = a + (++b2);
    cout << "sum1=" << sum1 << endl;

    cout << "sum2=" << sum2 << endl;
    cout << "b1=" << b1 << endl;
    cout << "b2=" << b2<< endl;
    return 0;
}

sum1=6;sum2=7;b1=b2=5;说明a++是先计算其它的,最后再把a的数值加一;而++a是先把a的数值加一然后一起计算。(总而言之,从左往右的顺序,遇见++就先把那个数加一,如果先遇到a那么就先计算那个式子)

又列如:


#include<iostream>
using namespace std;
int main()


{
 int a=5,a1 = 5, a2 = 5, b1 = 4, b2 = 4, b3 = 4;
 int sum1,sum2,sum3,sum4;
 sum1 = a > b1++ ? a : b2;
 sum2 = a>++ b3 ? a : b2;


sum3 = a2 > b2 ? ++a : b2;
 sum4 = a2 > b2 ? a1++ : b2;
 cout << "sum1=" << sum1 << endl;
 cout << "sum2=" << sum2<< endl;
 cout << "sum3=" << sum3 << endl;
 cout << "sum4=" << sum4 << endl;
 cout << "b1=" << b1 << endl;
 cout << "b2=" << b2<< endl;
 return 0;
}


有趣的:

#include<iostream>
using namespace std;
int main()

{
    int a = 5,b=5;
    int sum;
    sum = a > b++ ? a : b++;

    cout << "sum=" << sum << endl;

    cout << "b=" << b << endl;

    return 0;
}

sum=6,b=7

时间: 2024-10-29 04:57:07