2017-03-26 70 views
-1

我在C++的前綴n後綴中使用增量運算符,但即時得到不正確的結果,任何人都可以請指導我告訴我什麼即時做錯了:)謝謝:) 這裏是我的代碼:)用C++中的增量運算符得不到正確的結果

#include <iostream> 
using namespace std; 
int main() 
{ 
int a=0; 
cout<<a++<<endl<<++a<<endl; 
} 

期待結果

0 
2 

但即時得到結果

1 
2 
+0

'a ++'遞增'a'並返回其值爲1的副本,即1。 –

+0

兩種用途都在一個聲明內。你假設某種從左到右的順序是不正確的。 – stark

+0

@ Jaa-c它在返回之前返回值的副本,它應該是零。 –

回答

0

這與增量operator++做,它是如何發揮作用,取決於如果你把它當作前綴後綴

#include <iostream> 

int main() { 
    int a = 0; 
    std::cout << a++ << std::endl 
    // Output: 0. ++ as posfix creates an incremented copy of "a" and AFTER the line gets executed. 
    std::cout << ++a << std::endl; 
    // Output: 1. ++ as prefix creates a copy of "a", an incremented copy BEFORE the line gets executed. 

    std::cout << a++ << std::endl << ++a << std::endl; 
    // Output: 0 
    //   1. 
    // "a" get incremented only by the prefix operator++ 
} 

注:改變using namespace stdrecommend你使用的命名空間+範圍運算符,如用於C++標準庫容器的std::

+0

謝謝聖地亞哥瓦雷拉:) – Romeo

+0

沒有可能@Romeo。 Upvote請也:) – 0xDEFACED

+0

我upvoted :),但bcoz我有不到15聲望,得到的消息,它不會顯示 – Romeo