簡體   English   中英

無法交換數組元素C ++

[英]can not swap array elements 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;
}
#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;
}

有一些錯誤:

  • 您應該在循環內獲取輸入,然后將其分配給測試數組。
  • 打印交換值時,請使用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; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM