我正试图回答使用c ++语言的算法问题。问题是比较两个数组的每个元素并给出一个分数。基本上将第一个数组的第一个元素与第二个数组的第一个元素进行比较,并给出一些分数。如果第一个数组的第一个元素大于第二个数组的第一个元素,则第一个数组将获得一个分数。最后返回输出与这两个数组的分数之和。
我这样做了,但是不幸的是这段代码并没有给我我期望的答案。
#include <iostream>
int array_a[3] = { 6, 4, 6};
int array_b[3] = { 5, 4, 10};
int array_output[2] = {};
int main()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int z = 0; z < 2; z++) //z is for array_output[2]
{
if (array_a[i] > array_b[j])
{
array_output[z]++; //if int array_a[0] is bigger than int array_b[0] the first element of the output[0] receive +1
}
else if (array_a[i] == array_b[j])
{
array_output[z] = 0;//if the int array_a[1] and int array_b[1] are equal anyone receive score
}
else if (array_a[i] < array_b[j])
{
array_output[z]++; //if int array_a[2] is less than int array_b[2] the second element of the array_output receive +1
}
else
{
}
}
}
}
std::cout << "{" << array_output[0] << " , " << array_output[1] << "}";
std::cout << std::endl;
return 0;
}
输入int array_a [3] = {6,4,,6}和int array_b [3] = {5,4,,10}
我希望输出array_output [2] = {1,1}。
使用此代码,它们将返回array_output [2] = {4,4}
答案 0 :(得分:0)
如果要比较a.first与b.first,a.second与b.second,依此类推,那么一个循环就足够了;如果您只对总和感兴趣,那么即使结果数组也是多余的:
int main() {
int array_a[3] = { 4, 5, 6};
int array_b[3] = { 4, 6, 10};
int sum_a=0, sum_b=0;
for (int i = 0; i < 3; i++) {
if (array_a[i] > array_b[i]) {
sum_a++;
} else if (array_b[i] > array_a[i])
sum_b++;
}
std::cout << "sum a:" << sum_a << "; sum b:" << sum_b << std::endl;
}
答案 1 :(得分:0)
#include <iostream>
void compare(int array_a[], int array_b[]); //Function prototype
int main()
{
int array_al[3] = { 6, 4, 6 }; // array inputs
int array_bo[3] = { 5, 4, 10 };
compare(array_al, array_bo); //call the function compare
return 0;
}
void compare(int array_a[], int array_b[])
{
int al = 0, bo = 0;
for (int j = 0; j < 3; j++) // read and compare the values until reach the numbers of the elements
{
if (array_a[j] > array_b[j])
{
al++;
}
else if (array_a[j] < array_b[j])
{
bo++;
}
}
std::cout << "{" << al << " , " << bo << "}"; // print out the sum of the values
std::cout << std::endl;
}