#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);
}
答案 0 :(得分: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);
}
答案 1 :(得分: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);
}
}
答案 2 :(得分:4)
默认情况下,在UNIX中,浮点除零不会使程序停止异常。相反,它会生成infinity
或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;
答案 3 :(得分:1)
使用C99,您可以使用fetestexcept(2)
等等。