数组奇怪的行为

时间:2015-04-09 14:29:04

标签: c arrays primes

这是我的代码,它在运行时不起作用(在java工作正常)。

但如果我改变了行

primeNumber[size] = counter;

primeNumber[i] = counter;

程序在运行时不会崩溃。有人知道为什么C不接受该命令 primeNumber [size] = counter;

谢谢你!

#include <stdio.h>

int main(void){

int primeNumber[90];
primeNumber[0] = 2; //start with 2
int size = 1;
int divisible = 0;
int i = 0;
int counter = 3;


while(counter <= 100){
    divisible = 0;

    for(i = 0; i <= size; i++){
            if(counter%primeNumber[i] == 0){ 
                divisible++;
                break;      
            }
    }

    if(divisible == 0){ 
        primeNumber[size] = counter;
        size = size + 1;
    }       

    counter++;
}

for(i = 0; i <= size; i++){
    printf("\n prime: %d", primeNumber[i]);
}


return 0;
}   

3 个答案:

答案 0 :(得分:1)

这只是一个错误的错误。相关要点在下面的代码中进行了评论。

#include <stdio.h>

int main(void){

int primeNumber[90];
primeNumber[0] = 2; //start with 2
int size = 1;
int divisible = 0;
int i = 0;
int counter = 3;


while(counter <= 100){
    divisible = 0;

    for(i = 0; i < size; i++){ // Was error here
            if(counter%primeNumber[i] == 0){ 
                divisible++;
                break;      
            }
    }

    if(divisible == 0){ 
        primeNumber[size] = counter;
        size = size + 1;
    }       

    counter++;
}

for(i = 0; i < size; i++){ // Was error here
    printf("\n prime: %d", primeNumber[i]);
}


return 0;
}  

打印:

 prime: 2
 prime: 3
 prime: 5
 prime: 7
 prime: 11
 prime: 13
 prime: 17
 prime: 19
 prime: 23
 prime: 29
 prime: 31
 prime: 37
 prime: 41
 prime: 43
 prime: 47
 prime: 53
 prime: 59
 prime: 61
 prime: 67
 prime: 71
 prime: 73
 prime: 79
 prime: 83
 prime: 89
 prime: 97

答案 1 :(得分:1)

for循环中出现错误,初始值为size。由于您使用i <= sizei在第二次迭代期间到达1并且primeNumber[1]未初始化。请改用i < size

您在上一个for(使用printf)中遇到了同样的问题,因为您在更改size中的值后增加primeNumberprimeNumber[size]赢了&#39} t初始化。

注意:由于这个错误,您的代码应该只是异常行为,而不是崩溃。

答案 2 :(得分:0)

大小的值增长到98,而数组的大小是90,所以将大小增加到100,这将解决你的问题。

#include <stdio.h>

int main(void){

int primeNumber[100]; //increased size to 100
primeNumber[0] = 2; //start with 2
int size = 1;
int divisible = 0;
int i = 0;
int counter = 3;


while(counter <= 100){
    divisible = 0;
    //replaced <= with < to avoid floating     point exception
    for(i = 0; i < size; i++){ 
            if(counter % primeNumber[i] == 0){
                divisible++;
                break;
            }
    }

    if(divisible == 0){
        primeNumber[size] = counter;
        size = size + 1;
    }

    counter++;
}

for(i = 0; i <= size; i++){
    printf("\n prime: %d", primeNumber[i]);
}
return 0;
}