2015-10-01 59 views
1

我是C++新手。我試圖解決教科書中的問題:交換數組中的第一個和最後一個元素。但是當我運行我寫的代碼時,什麼都沒有發生,甚至「請輸入數組中的數字:」這句話也沒有出現。任何人都可以提供幫助?謝謝。不能交換數組元素C++

#include <iostream> 

using namespace std; 

int swap(int values[], int size) 
{ 
    int temp = values[0]; 
    values[0] = values[size-1]; 
    values[size-1] = temp; 
} 

int main() 
{ 
    const int SIZE = 5; 
    int test[SIZE]; 
    cout << "Please enter the numbers in the array: " << endl; 
    int input; 
    cin >> input; 
    for(int i=0; i<SIZE; i++) 
    { 
      test[i] = input; 
    } 
    swap(test, SIZE); 
    cout << test[SIZE] << endl; 
    return 0; 
} 
+0

上有[Wandbox](http://melpon.org/wandbox/permlink/s4BjWjV9SVjoKkAl)一些輸出。無論如何,cout <<測試[SIZE] << endl;'超出範圍,這是不好的。 – MikeCAT

+1

'swap()'有一個不是void的返回類型,但不返回任何東西。 –

+0

此外,您可以在所有單元格中使用相同的單個輸入值填充陣列。交換單元格不會產生可見的結果。 – CygnusX1

回答

1
#include <iostream> 

using namespace std; 

//Here return type should be void as you are not returning value. 
void swap(int values[], int size) 
{ 
    int temp = values[0]; 
    values[0] = values[size-1]; 
    values[size-1] = temp; 
} 

int main() 
{ 
    const int SIZE = 5; 
    int test[SIZE]; 
    cout << "Please enter the numbers in the array: " << endl; 

    //USE LOOP TO TAKE INPUT ONE BY ONE IN AN ARRAY 
    for(int i = 0; i < SIZE; i++) 
    cin >> test[i]; 

    swap(test, SIZE); 

    //USE LOOP TO DISPLAY ELEMENT ONE BY ONE 
    for(int i = 0; i < SIZE; i++) 
    cout << test[i] << endl; 

    return 0; 
} 
+1

或許'size'而不是'SIZE'? ALL-CAPS標識符最好是爲宏保留的。 – Andrew

+1

而在C++ 11中:'for(auto&e:test)std :: cin >> e;交換(測試,SIZE); for(auto e:test)std :: cout << e << std :: endl;' – Jarod42

1

有幾個錯誤:

  • 你應該得到循環內的輸入,然後將其分配給測試陣列。
  • 當打印交換值,訪問測試陣列SIZE-1代替SIZE,因爲數組索引運行從0SIZE-1,包括端值。
  • 您聲明swap()返回int,但沒有提供return語句(這表明您沒有從您的編譯器啓用足夠的警告)。

    #include <iostream> 
    
    using namespace std; 
    
    void swap(int values[], int size) 
    { 
        int temp = values[0]; 
        values[0] = values[size-1]; 
        values[size-1] = temp; 
    } 
    
    int main() 
    { 
        const int SIZE = 5; 
        int test[SIZE]; 
        int input; 
        cout << "Please enter the numbers in the array: " << endl; 
    
        for(int i=0; i<SIZE; i++) 
        { 
          cin >> input; 
          test[i] = input; 
        } 
        swap(test, SIZE); 
        cout << test[SIZE-1] << endl; 
        return 0; 
    }