c ++比较数组的总和

时间:2013-03-04 09:02:07

标签: c++ algorithm

我有2个数组,每个数组有5个整数,我如何比较两个数组,以便数组A大于数组B,以下是我的代码,我得到返回0:

#include <iostream>
using namespace std;

int main()
{
    const int AMAX = 5, BMAX = 6;
    int i;
    bool c1 = true, c2 = false;
    int A[AMAX] = { 1, 2, 3, 4, 5 };
    int B[BMAX] = { 6, 7,8, 9, 1};

    for (i = 0; i < BMAX; i++)
        if (B[i] == A[i])       
            cout << c1 << endl;
        else
            cout << c2 << endl;
    return 0;
}

我在这里缺少什么?

更新

#include <iostream>
using namespace std;
int main(){
  int a[] = {6,7,29};
  int b[] = {3,2,11};
  int acc1=0;
  int acc2 = 0;
  for (int i=0;i<3;i++){
    acc1+=a[i];
}
  for(int j=0;j<3;j++){
    acc2+=b[j];
}

if(acc1 < acc2){
  printf("Array B is greater than Array B ");
}

else{
  printf("Array B greater than Array A");
}

  return 0;
}

3 个答案:

答案 0 :(得分:1)

您可以使用内置算法std::equal来比较两个数组。例如:

#include <iostream>
#include <algorithm>
using namespace std;
#define countof(x) sizeof(x)/sizeof(x[0])
int main()
{
    int A[] = { 2, 4, 1, 5, 9 };
    int B[] = { 9, 12, 32, 43, 23};
    int C[] = { 2, 4, 1, 5, 9 };
    cout << equal(A, A + countof(A), B) << endl;
    cout << equal(A, A + countof(A), C) << endl;
}

输出:0 1

答案 1 :(得分:1)

如果要比较的是数组中元素的 sums (即确定A中所有元素的总和是否大于B中所有元素的总和{1}}),正如问题的标题似乎暗示,这应该做你想要的:

#include <iostream>
#include <algorithm>
#include <numeric>
#include <iomanip>

int main()
{
    using namespace std;

    int A[] = { 2, 4, 1, 5, 9 };
    int B[] = { 9, 12, 32, 43, 23};

    int sumA = accumulate(begin(A), end(A), 0);
    int sumB = accumulate(begin(B), end(B), 0);

    cout << boolalpha << (sumA > sumB);

    return 0;
}

如果您不使用C ++ 11,这是用C ++ 03编写的等效程序:

#include <iostream>
#include <numeric>

int main()
{
    using namespace std;

    int A[] = { 2, 4, 1, 5, 9 };
    int B[] = { 9, 12, 32, 43, 23};

    int sumA = accumulate(A, A + sizeof(A) / sizeof(int), 0);
    int sumB = accumulate(B, B + sizeof(B) / sizeof(int), 0);

    cout << ((sumA > sumB) ? "true" : "false");

    return 0;
}

答案 2 :(得分:0)

#include <iostream>
using namespace std;
int main()
{
int suma;
int sumb;

int A[] = { 2, 4, 1, 5, 9 };
int B[] = { 9, 12, 32, 43, 23};

suma = accumulate(A, A + sizeof(A) / sizeof(int), 0);
sumb = accumulate(B, B + sizeof(B) / sizeof(int), 0);

cout << ((sumA > sumB) ? "true" : "false");

return 0;
}