无法初始化C ++数组

时间:2013-12-27 21:02:08

标签: c++ arrays algorithm indexing

我正在尝试数组中的哪些元素(也是斐波那契数字)是素数或复合数。

我得到整数的数组[1 ... N]。我应该编写algoritm,返回如果在数组中的信息: - 所有元素,其索引是Fibonacci数之一是复合数。 - 其余索引中至少有一个是素数。 我在int main()得到一个错误: 不能在赋值中将''转换为'int'并且:初始化值太多。 我的代码如下:

#include <iostream>
#include <cstdlib>
using namespace std;
const int N = 5;
void function1(int tab[]);
bool function2(int tab[], int);
int main() {

    int tab[N], i;
    tab[N] = { 4, 8, 12, 16, 13 };
    function1(tab);
    system("pause");
    return 0;
}

void function1(int tab[]) {
    int a, b, x, i;
    bool g = 1;
    for ( i = 0; i < N, g == 1; i++) {
        a = 0;
        b = 1;
        while (i < a && i < b) {
            a = a + b;
            b = a + b;
        }
        if (i == b || i == a) {
            x = function2(tab, i);
        }
        if (!x) {
            cout << "NO";
            g = 0;
        }
    }
    int licz_pier = 0;
    i = 0;
    if (g) {
        while (i < N && licz_pier == 0) {
            if (tab[i] != 0) {
                if (function2(tab, i)) {
                    i++;
                }
                else {
                    licz_pier = 1;
                    cout << "yes" << endl;
                }
            }
        }
    }

}

bool function2(int tab[], int i) {
    int k = 2;
    bool x = 1;
    while (k < sqrt(tab[i]) && x == 1) {
        if (tab[i] % k == 0) {
            x = 0;
            tab[i] = 0;
                return 1;
        }
        k = k + 1;
    }

    if (x) {
        return 0;
    }
    return 0;
}

PS。我是初学者,这是我的第一篇文章,对不起我的英文。

1 个答案:

答案 0 :(得分:3)

声明

tab[N] = { 4, 8, 12, 16, 13 };

不合法。您需要将初始化放在定义中:

int tab[N] = { 4, 8, 12, 16, 13 };

在声明后逐个手动初始化数组:

tab[0] = 4;
tab[1] = 8;
tab[2] = 12;
tab[3] = 16;
tab[4] = 13;