不能交换数组元素 C++

can not swap array elements c++

本文关键字:C++ 数组元素 能交换 不能      更新时间:2023-10-16

我是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;
}

有几个错误:

  • 您应该在循环中获取输入,然后将其分配给测试数组。
  • 打印交换值时,使用 SIZE-1 而不是 SIZE 访问测试数组,因为数组索引从 0 运行到 SIZE-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;
    }
    
#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;
}