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

    fx=10/x;

    if(10 is divided by zero)// I dont know what to put here please help
        printf("division by zero is not allowed");
    else
        printf("f(x) is: %.5f",fx);

}
4

4 回答 4

8
#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);

}
于 2010-03-21T01:59:26.107 回答
6

这应该这样做。在执行除法之前,您需要检查是否被零除。

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);
    }
}
于 2010-03-21T01:58:48.510 回答
4

默认情况下,在 UNIX 中,浮点除以零不会因异常而停止程序。相反,它产生的结果是infinityor NaN。您可以使用isfinite.

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

或者,您可以检查除数是否不为零:

if ( z == 0 || ! isfinite( z ) ) cerr << "invalid divisor to division" << endl;
x = y / z;
于 2010-03-21T02:05:05.743 回答
1

使用 C99,您可以使用fetestexcept(2)等。

于 2010-03-21T02:00:48.117 回答