我在C++的前綴n後綴中使用增量運算符,但即時得到不正確的結果,任何人都可以請指導我告訴我什麼即時做錯了:)謝謝:) 這裏是我的代碼:)用C++中的增量運算符得不到正確的結果
#include <iostream>
using namespace std;
int main()
{
int a=0;
cout<<a++<<endl<<++a<<endl;
}
期待結果
0
2
但即時得到結果
1
2
我在C++的前綴n後綴中使用增量運算符,但即時得到不正確的結果,任何人都可以請指導我告訴我什麼即時做錯了:)謝謝:) 這裏是我的代碼:)用C++中的增量運算符得不到正確的結果
#include <iostream>
using namespace std;
int main()
{
int a=0;
cout<<a++<<endl<<++a<<endl;
}
期待結果
0
2
但即時得到結果
1
2
這與增量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 std
我recommend你使用的命名空間+範圍運算符,如用於C++標準庫容器的std::
。
'a ++'遞增'a'並返回其值爲1的副本,即1。 –
兩種用途都在一個聲明內。你假設某種從左到右的順序是不正確的。 – stark
@ Jaa-c它在返回之前返回值的副本,它應該是零。 –