[英]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
訪問測試數組,因為數組索引的范圍是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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.