C programming - floating point exception

后端 未结 5 422
生来不讨喜
生来不讨喜 2021-01-03 06:14
matthewmpp@annrogers:~/Programming/C.progs/Personal$ cat prime4.c
/*
 * File:   main.c
 * Author: matthewmpp
 *
 * Created on November 7, 2010, 2:16 PM
 */

#include         


        
相关标签:
5条回答
  • 2021-01-03 06:28
    sqrt(x) needs x to be of type double, you have used int.
    

    Cast to double (double)n_prmfnc

    I am VERY sure about this !

    0 讨论(0)
  • 2021-01-03 06:37

    What happens is a division by zero. You only initialise the first three entries of primes_pf, but iterate over all of them (actually, your loop runs even one past the last entry; use i < 100 instead of i <= 100 to fix this). For all but the first three entries, you divide by some unitialised quantity, and one of the entries apparently happens to be zero. Don't use unitialised values.

    0 讨论(0)
  • 2021-01-03 06:38

    "Floating point exception" is a misnomer. It only happens on integer division by zero and a few other division-related operations.

    0 讨论(0)
  • 2021-01-03 06:39

    The problem exists in your primes_pf variable. You seemed to have initialized the first three elements of this integer array, but when iterator i goes beyond 2, primes_pf[i] is reading from uninitialized memory and getting compared to sq_root_pf; that can't be right.

    I haven't taken the time to fully understand your algorithm but my best guess is that you forgot to assign a new value to primes_pf somewhere in your for loop.

    0 讨论(0)
  • 2021-01-03 06:50

    Not sure I believe the answer above!

    X = 5.0; Y = 0.0; Z = X/Y;

    This will give a floating point exception....

    The problem would appear to be that prime_pf is only initialised for 3 elements. So the modulo is attempting to divide by zero. BTW, if you add \n to your printf statement, and add the extra statement fflush(stdout); you are more likely to see the debug output before the program errors.

    0 讨论(0)
提交回复
热议问题