检查阵列位置

时间:2014-07-12 15:25:21

标签: c++ arrays

我正在执行程序,我正在检查数组是否与数组一样平衡 int a5[] = {2, 1, 4, 3}; // balance array because i got even number on even position so program return 1 int a5[] = {3, 1, 4, 3}; // un balance array because i got odd number on even position so program return 0

这是我正在尝试的程序

int araay(int arg[], int length);
int main()
{

    int a6[] = {3, 3, 4, 4};
    int a7[] = {2, 2, 3, 4};
    int a8[] = {4, 1, 2, 3};
    int a9[] = {1, 1};
    araay (a7,sizeof(a7));

}

int araay (int arg[], int length)
{
    int sumEven = 0;
    int sumOdd = 0;

    for (int i=0; i<=length; i=i+2)
    {
        if (arg[i]%2 == 0)
        {
            sumEven++;
        }
        else
            sumOdd++;
    }
    for (int i=1; i<=length; i=i+2)
    {
        if (arg[i]%2 == 0)
        {
            sumEven++;
        }
        else
            sumOdd++;
    }
    return 0;   
}

作为回报,它总是每次都给我00000返回零值

3 个答案:

答案 0 :(得分:3)

以下可能有所帮助:(http://ideone.com/NttqbY

bool is_balanced(const std::vector<std::size_t>& v)
{
    for (std::size_t i = 0; i != v.size(); ++i) {
        if ((i % 2) != (v[i] % 2)) {
            return false;
        }
    }
    return true;
}

答案 1 :(得分:2)

感谢大家的意见和帮助

这是我试过的

int araay(int arg[], int length);
int main()
{

    int a6[] = {3, 3, 4, 4};
    int a7[] = {2, 3, 2, 3};
    int a8[] = {4, 1, 2, 3};
    int a9[] = {1, 1};
    araay (a7,3);


}

int araay (int arg[], int length)
{
    int sumEven = 0;
    int sumOdd = 0;

    for (int i=0; i<=length; i+=2)
    {
        if (arg[i]%2 != 0)
        {
            cout<<"unbalanced"<<endl;
        //  return 0;

        }
        else
        {
            sumEven++;
        }
    }
    for (int i=1; i<=length; i=i+2)
    {
        if (arg[i]%2 == 0)
        {
            cout<<"unbalanced"<<endl;
            sumEven++;
        }
        else
        {
            sumOdd++;
        //  return 0;
        }
    }

    return 0;
}

但@jarod的答案看起来更合适,更轻松

答案 2 :(得分:0)

这是你可以做的

#include <iostream>

int check(int arg[])
{
    for (auto i = 0; i < sizeof(arg); ++i)
    {
        if ((i % 2) != (arg[i] % 2))
        {
            return 0;
        }
    }
    return 1;
}

void main()
{
    int a[] = { 1, 2, 3, 4 };
    int b[] = { 2, 3, 4, 5 };
    int c[] = { 2, 2, 3, 3 };

    std::cout << "a = " << check(a) << std::endl;
    std::cout << "b = " << check(b) << std::endl;
    std::cout << "c = " << check(c) << std::endl;

    getchar();
}