gpt4 book ai didi

c++ - 如何找到两个不同数组中交换的值?

转载 作者:行者123 更新时间:2023-11-30 05:38:36 24 4
gpt4 key购买 nike

我想用一个数组中的赔率和另一个数组中的偶数交换一个数组,同时跟踪计数和被交换的值。

{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;
}

到目前为止,我已经让 swapcounter 正常工作,但我似乎无法弄清楚:

如何查找和存储交换元素的各个值? (我只能得到一个值来显示。)

我能得到任何关于如何获取所有值的提示吗?除了输入和输出流,我不允许使用任何额外的库。提前致谢。

最佳答案

创建一个辅助数组 swapbool,如果交换完成则设置 boolean = 1。

#include<iostream>
using namespace std;
int main() {
int a1[3] = { 2, 3, 6 };
int a2[3] = { 1, 4, 7 };
int swapbool[3] = {0,0,0};
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;
swapbool[i]=1;
}
}

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;
for (int i = 0; i < 3; i++) {
if(swapbool[i] == 1)
{
std::cout << "swapvalue1-> " << a2[i] << endl;
std::cout << "swapvalue2-> " << a1[i] << endl;
}
}

//std::cout << "swap value: " << swapvalue << endl;
}

关于c++ - 如何找到两个不同数组中交换的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32664483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com