简体   繁体   中英

How to fix Floating point exception: 8 in C code

I'm trying to write a program that lists all prime numbers in a given parameter. My terminal won't output anything, even though I have a print function at the end of the program.

Could you also let me know if the x and g variables were necessary or could I have just stuck with i.

Here's my code:

#include <stdio.h>

#define MAX_SIZE 1000
int main(){

    int N , i, x, g, a[MAX_SIZE];

    scanf("%d", &N);

    a[0] = 2;

    for (i = 1; i < N - 2; i++)
    {
        a[i] = (a[i-1]) + 1;
    }

    for (x = 0; x < N - 2; x++){
        for (i = 1; i < N - 2; i++){
            if (a[i] % a[x] == 0) {
                for (g = i; g < N - 2; g++){
                    a[g] = a[g+1];
                }
            }
        }
    }


    for (i = 0; i < N - 2; i++){
        printf("%d \n", a[i]);
    }

   return 0;
}

You have off-by-one error here:

for (g = i; g < N - 2; g++){
  a[g] = a[g+1];

}

When g = N - 2 - 1 , the value a[N - 2] is used, but the element is not initialized and the value is indeterminate.

You should check and fix your algorithm not to read uninitialized element.


Your code looks too complicated for me. Here is an example of my code to print all prime numbers that are N or less:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int N;
    int* primes;
    int prime_count;
    int i, j;
    if (scanf("%d", &N) != 1) return 1;
    primes = malloc(sizeof(*primes) * N);
    if (primes == NULL) return 2;

    prime_count = 0;
    for (i = 2; i <= N; i++) {
        int is_prime = 1;
        for (j = 0; j < prime_count; j++) {
            if (i % primes[j] == 0) {
                is_prime = 0;
                break;
            }
        }
        if (is_prime) primes[prime_count++] = i;
    }

    for (i = 0; i < prime_count; i++) {
        printf("%d\n", primes[i]);
    }

    free(primes);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM