【发布时间】:2015-09-19 15:51:10
【问题描述】:
我想用一个数组中的赔率和另一个数组中的偶数交换一个数组,同时跟踪计数和被交换的值。
{2, 3, 6}
{1, 4, 7}
will become
{1, 3, 7}
{2, 4, 6}
有 2 次交换,交换的值是
1 &2, 6 & 7.
int main() {
int a1[3] = { 2, 3, 6 };
int a2[3] = { 1, 4, 7 };
int i;
int swapcount = 0;
int swapvalue;
std::cout << "Before swap:\n" << endl;
std::cout << "Array 1:\n" << endl;
for (int i = 0; i < 3; i++) {
cout << " " << a1[i] << endl;
}
std::cout << "Array 2:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a2[i] << endl;
}
for (int i = 0; i < 3; i++) {
if (a1[i] % 2 != 1) {
swapcount++;
int temp = a1[i];
a1[i] = a2[i];
a2[i] = temp;
swapvalue = i;
}
}
std::cout << "After swap:\n" << endl;
std::cout << "Array 1:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a1[i] << endl;
}
std::cout << "Array 2:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a2[i] << endl;
}
std::cout << "swap count: " << swapcount << endl;
std::cout << "swap value: " << swapvalue << endl;
}
到目前为止,我已经让 swap 和 counter 工作,但我似乎无法弄清楚:
如何查找和存储被交换元素的各个值? (我只能显示一个值。)
我能得到任何关于如何获取值的提示吗?除了输入和输出流之外,我不允许使用任何其他库。提前谢谢。
【问题讨论】: