帮助打印反向数组 [英] Help to print reverse array
本文介绍了帮助打印反向数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
#include <iomanip>
using namespace std;
const int sentinel = 0;
const int arraysize = 10;
int main()
{
cout << fixed << showpoint << setprecision(2); // format to 2 decimals
int array[arraysize]; // declare an array item of 10 components
int number;
int count = 0;
for ( int i = 0; i < arraysize; i++)
array[i] = 0;
cout <<"Please enter ints, " << sentinel << " to quit: ";
cin >> number;
while (number != sentinel && count < arraysize)
{
array[count++] = number;
cin >> number;
}
cout << endl;
cout << "The original array: ";
for (int i = 0; i < count; i++)
cout << array[i] << ' ';
cout << endl;
int temp;
for (int i = 0; i < arraysize/2; i++)
{
temp = array[arraysize-1-i];
array[arraysize - i - 1] = array[i];
array[i] = temp;
}
cout << "The reverse array: ";
for (int i = 0; i < arraysize; i++)
cout << array[i]<< ' ';
cout << endl;
return 0;
}
我的尝试:
我试图打印反向,如果原始值是1 2 3 4 5 6然后我想反向数组是6 5 4 3 2 1不是0 0 0 0 6 5 4 3 2 1
What I have tried:
I tried to print reverse if the original value is 1 2 3 4 5 6 then I want reverse array to be 6 5 4 3 2 1 not 0 0 0 0 6 5 4 3 2 1
推荐答案
使用count
- 用户输入的元素数 - 而不是arraysize 中的
循环:
Usecount
- the number of elements the user entered - instead ofarraysize
in yourfor
loops:
for (int i = 0; i < count/2; i++)
{
temp = array[count-1-i];
array[count - i - 1] = array[i];
array[i] = temp;
}
cout << "The reverse array: ";
for (int i = 0; i < count; i++)
{
cout << array[i]<< ' ';
}
我会尝试类似的东西。
I would try something like that.
int temp;
for (int i = 0; i < count/2; i++)
{
temp = array[count-1-i];
array[count - i - 1] = array[i];
array[i] = temp;
}
cout << "The reverse array: ";
for (int i = 0; i < count; i++)
cout << array[i]<< ' ';
cout << endl;
你知道,你的代码可以用这种方式重写:
You know, your code could be rewritten this way:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
const int sentinel = 0;
int n;
vector <int> v;
cout <<"Please enter ints, " << sentinel << " to quit: " << endl;
do
{
cin >> n;
if ( n ) v.push_back(n);
} while (n);
cout << "the original array : ";
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
cout << *it << " ";
cout << endl;
cout << "the reverse array : ";
for (vector <int>:: reverse_iterator it = v.rbegin(); it != v.rend(); it++)
cout << *it << " ";
cout << endl;
}
这篇关于帮助打印反向数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文