问题描述
我有我试图扭转数的数组。我相信我的code的作用是正确的,但我不能得到正确的输出。
输出写着:10 9 8 7 6。
为什么我不能得到的数字的另一半?当我删除/ 2计数,输出写着:10 9 8 7 6 6 7 8 9 10
无效逆向(INT [],int);在诠释的main()
{
const int的SIZE = 10;
INT ARR [尺寸] = {1,2,3,4,5,6,7,8,9,10}; 反向(ARR,SIZE);
返回0;
}
void反转(INT ARR [],诠释计数)
{
INT温度;
的for(int i = 0; I<计数/ 2; ++ I)
{
改编[I] =温度;
TEMP = ARR [COUNT-I-1];
ARR [COUNT-I-1] =改编[I];
改编[I] =温度; COUT<<温度<< ;
}
}
行
改编[I] =温度;
是错误的。 (在你的循环的第一次迭代它集改编[I]
为不确定的值;进一步的迭代将其设置为不正确的值)。如果删除此行,您的阵列应正确逆转。
在这之后,你应该移动code打印出反向排列到一个新的循环,从而遍历整个列表。您当前的code只打印第一计数/ 2
元素。
INT温度,I;
对于(i = 0; I<计数/ 2; ++ I){
TEMP = ARR [COUNT-I-1];
ARR [COUNT-I-1] =改编[I];
改编[I] =温度;
}
对于(i = 0; I<计数; ++ I){
COUT<<改编[1] - ;&下; ;
}
I have an array of numbers that I am trying to reverse. I believe the function in my code is correct, but I cannot get the proper output.
The output reads: 10 9 8 7 6.Why can't I get the other half of the numbers? When I remove the "/2" from count, the output reads: 10 9 8 7 6 6 7 8 9 10
void reverse(int [], int);
int main ()
{
const int SIZE = 10;
int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
reverse(arr, SIZE);
return 0;
}
void reverse(int arr[], int count)
{
int temp;
for (int i = 0; i < count/2; ++i)
{
arr[i] = temp;
temp = arr[count-i-1];
arr[count-i-1] = arr[i];
arr[i] = temp;
cout << temp << " ";
}
}
The line
arr[i] = temp;
is wrong. (On the first iteration of your loop it sets arr[i]
to an undefined value; further iterations set it to an incorrect value.) If you remove this line, your array should be reversed correctly.
After that, you should move the code which prints the reversed array into a new loop which iterates over the whole list. Your current code only prints the first count/2
elements.
int temp, i;
for (i = 0; i < count/2; ++i) {
temp = arr[count-i-1];
arr[count-i-1] = arr[i];
arr[i] = temp;
}
for (i = 0; i < count; ++i) {
cout << arr[i] << " ";
}
这篇关于在阵列逆向内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!