不能交换数组元素 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;
}
有几个错误:
- 您应该在循环中获取输入,然后将其分配给测试数组。
- 打印交换值时,使用
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;
}
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int