how to check if there is a division by zero in c

前端 未结 4 1912
暖寄归人
暖寄归人 2021-01-05 08:21
#include
void function(int);

int main()
{
     int x;

     printf(\"Enter x:\");
     scanf(\"%d\", &x);

function(x);

return 0;
}

void functi         


        
相关标签:
4条回答
  • 2021-01-05 08:52

    By default in UNIX, floating-point division by zero does not stop the program with an exception. Instead, it produces a result which is infinity or NaN. You can check that neither of these happened using isfinite.

    x = y / z; // assuming y or z is floating-point
    if ( ! isfinite( x ) ) cerr << "invalid result from division" << endl;
    

    Alternately, you can check that the divisor isn't zero:

    if ( z == 0 || ! isfinite( z ) ) cerr << "invalid divisor to division" << endl;
    x = y / z;
    
    0 讨论(0)
  • 2021-01-05 08:54

    With C99 you can use fetestexcept(2) et alia.

    0 讨论(0)
  • 2021-01-05 08:59

    This should do it. You need to check for division by zero before performing the division.

    void function(int x)
    {
        float fx;
    
        if(x == 0) {
            printf("division by zero is not allowed");
        } else {
            fx = 10/x;
            printf("f(x) is: %.5f",fx);
        }
    }
    
    0 讨论(0)
  • 2021-01-05 09:01
    #include<stdio.h>
    void function(int);
    
    int main()
    {
         int x;
    
         printf("Enter x:");
         scanf("%d", &x);
    
    function(x);
    
    return 0;
    }
    
    void function(int x)
    {
        float fx;
    
        if(x==0) // Simple!
            printf("division by zero is not allowed");
        else
            fx=10/x;            
            printf("f(x) is: %.5f",fx);
    
    }
    
    0 讨论(0)
提交回复
热议问题