简体   繁体   中英

floating point exception in C code

#include <stdio.h>
int test1(int x, int n){
    int times=31/n;
    return ((1-(1<<(n*times)))/(1-(1<<n)));
}

I am doing a calculation where 1<=n<=32

It only works when 1<=n<=31, how can I change it for n=32? As I test its n=32 case in xcode, it triggers the debugger and shows thread 1 exc_arithmetic(code=exc_i386_div....
Thank you in advance.

There is a decent chance that when you do 1 << 32 , it is treated as 1 << 0 (and, since you're invoking undefined behaviour, that's OK), and you then get the 'floating point exception' because you are doing an integer 'divide by zero'. These days, that's the most common cause for the exception. If you were doing floating-point arithmetic, you'd get an infinity returned (silently) for division by zero.

I just found out how I can fix this. the problem is 1<<32 case (which I will try to avoid).

I changed 1 << n to (1 << (n-1) )*2 , another way to apply the math.

return ((1-(1<<(n*times)))/(1- (1<<(n-1))*2  ));

Some modern implementations for 2's-complement platforms generate a "floating point exception" in response to integer division overflow that occurs in the following code

int a = INT_MIN;
int b = -1;
int c = a / b;

even thought there's nothing "floating" there. GCC is one example of such platform.

Apparently, your expression runs into the same kind of problem as a practical platform-specific manifestation of undefined behavior triggered by "overshifting" an integer.

PS As noted by @Jonathan Leffler, integer division by zero also generates a "floating point exception" in GCC, which is probably even more likely to occur in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM