简体   繁体   English

如何修复浮点异常:C 代码中的 8

[英]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.您能否也让我知道 x 和 g 变量是否必要,或者我是否可以坚持使用 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.g = N - 2 - 1 ,使用值a[N - 2] ,但元素未初始化且值不确定。

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:这是我的代码示例,用于打印N或更少的所有素数:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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