如何检查c中是否有除零
#include 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); }
#include 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); }
这应该做到这一点。 在执行除法之前,您需要检查除零。
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); } }
默认情况下,在UNIX中,浮点除零不会使程序停止exception。 相反,它产生的结果是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;
使用C99,您可以使用fetestexcept(2)
等。