【发布时间】:2021-11-06 10:33:29
【问题描述】:
我希望找到一个替代解决方案/方法来挖掘,以在给定参数的情况下解决上述问题。基本上我的方法是同时遍历两个数组并添加相应的值。首先是使用条件运算符。
#include <iostream>
#include <array>
using namespace std;
//an array of size 0 [no elements]
void myLists(int list1[], int list2[], int list3[], int size)
{
for (int i = 0; i < size; i++)
{
if ((list1[i] + list2[i]) % 2 == 0) // return the modulo of the two array sums
{
cout << (list3[i] == true);
}
else
{
cout << (list3[i] == false);
};
}
}
int main()
{
//initialize the two arrays
int list1[5]{1, 2, 3, 4, 5};
int list2[5]{0, 4, 6, 8, 10};
int list3[5]{};
int size{};
size = sizeof(list1) / sizeof(list1[0]);
myLists(list1, list2, list3, size);
return 0;
}
代码结果:
10101
【问题讨论】:
-
我认为您的代码似乎是巧合,但实际上是错误的。
-
不管怎样,
list3在这个程序中从未被修改过,尽管要求它被填充。每个list3[i]都可以替换为0。可能list3[i] ==本来是list3[i] =。 -
该算法存在:标准库
std::transform -
@GDube 你的教授正试图给你一个提示,我建议你阅读Two's complement
-
就在
for循环的开始处:list3[i]= (list1[i] + list2[i]) % 2;然后,if条件变为if(list[3] == 1)
标签: c++ arrays algorithm for-loop function-definition