崩潰日志
Invalid number value (NaN) in JSON write-[NSDictionary(JSON)GZ_ toJsonString]
對(duì)NaN進(jìn)行了json轉(zhuǎn)換導(dǎo)致崩潰
什么是NaN 和 +inf
nan: not a number 不是數(shù)字
inf: infinity 無(wú)窮
inf一般是因?yàn)榈玫降臄?shù)值,超出浮點(diǎn)數(shù)的表示范圍(溢出会宪,即階碼部分超過(guò)其能表示的最大值)研儒;而nan一般是因?yàn)閷?duì)浮點(diǎn)數(shù)進(jìn)行了未定義的操作煤篙,如對(duì)-1開方
導(dǎo)致項(xiàng)目中崩潰的代碼
CMTime time = CMTimeMake(10, 0);
CGFloat videoLength = round(time.value*1.0/time.timescale);
10和0是后臺(tái)傳回?cái)?shù)據(jù)幅恋,導(dǎo)致算出的videoLength = NaN
OC 什么時(shí)候會(huì)產(chǎn)生這兩種情況
- num/0 分母是零
- 對(duì)負(fù)數(shù)開平方
- 數(shù)學(xué)函數(shù)不正確運(yùn)算
1/0可能出現(xiàn)的值
int i1 = 1/0;
NSInteger n1 = 1/0;
CGFloat cf1 = 1/0;
double d1 = 1/0;
float f1 = 1/0;
結(jié)果全部是0
各種類型 變量/0 或者變量/0.0
int ia = 1;
NSInteger na = 1;
CGFloat cfa = 1.0;
double da = 1.0;
float fa = 1.0;
int ria = ia/0; //-374309760
NSInteger rna = na/0; //0
CGFloat rcfa = cfa/0; //+inf
double rda = da/0; //+inf
float rfa = fa/0; //+inf
rcfa = cfa/0.0; //+inf
rda = da/0.0; //+inf
rfa = fa/0.0; //+inf
int ria1 = ia/0; //0
int rna1 = na/0; //32671
int rcfa1 = cfa/0; //-2147483648
int rda1 = da/0; //-2147483648
int rfa1 = fa/0; //-2147483648
變量/變量 第二個(gè)變量是0或者0.0
int ia = 1;
NSInteger na = 1;
CGFloat cfa = 1.0;
double da = 1.0;
float fa = 1.0;
int zi = 0;
double zd = 0.0;
int ria2 = ia/zi; //crash: Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
NSInteger rna2 = na/zi; //crash: Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
CGFloat rcfa2 = cfa/zi; //+inf
double rda2 = da/zi; //+inf
float rfa2 = fa/zi; //+inf
int ria3 = ia/zd; //-2147483648
NSInteger rna3 = na/zd; //-9223372036854775808
CGFloat rcfa3= cfa/zd; //+inf
double rda3 = da/zd; //+inf
float rfa3 = fa/zd; //+inf
// NSData *json1 = [NSJSONSerialization dataWithJSONObject:@{@"key":@(inf)} options:NSJSONWritingPrettyPrinted error:nil];
產(chǎn)生 NaN的情況
CMTime time = CMTimeMake(10, 0);
CGFloat videoLength = round(time.value*1.0/time.timescale);
結(jié)論
浮點(diǎn)數(shù)類型除以0 產(chǎn)生 +inf ,對(duì)這個(gè)值@{@“key”:@(+inf)} 進(jìn)行json處理也會(huì)導(dǎo)致崩潰赢笨。
變量 /變量(0)會(huì)崩潰 crash: Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
變量 /變量(0.0)不崩潰腌闯,會(huì)產(chǎn)生隨機(jī)數(shù)著洼。
NaN或者+inf并不會(huì)直接導(dǎo)致崩潰樟遣,但是在后期運(yùn)算中可能導(dǎo)致崩潰
解決辦法
數(shù)學(xué)計(jì)算時(shí),對(duì)分母進(jìn)行判斷 是否為0
判斷數(shù)據(jù)
if (isnan(a)) {
NSLog(@"NaN");
}
if (isinf(b)) {
NSLog(@"+inf");
}