抓狂 对浮点数使用 abs 函数求绝对值的代价

               

因程序需要,需求出浮点数的绝对值~

第一个想到的函数就是 abs(),不料无论怎么求,abs出来的结果都是0!!

是的,就是0!!

真是他妈的太奇怪了,我检查了一遍又一遍,代码的写法没有发现任何的问题,

可以求出来的结果他妈的就是0!!!

白白浪费了哥1个半小时以上,不泻泻火还真是他妈的受不了!!

这次我是真的学乖了,今后不管遇到了什么问题,10分钟每搞出来马上去google查!!

不过也得到了一些意外的收获,那就是我写的那块儿原来没我想地那么复杂,

基本上,求浮点数绝对值地问题解决了以后,将游戏安装到机器上得到地效果已经是相当地棒了。。

一句话,问题解决了就好。。。其实这次犯在这个问题上面还是怪自己太执拗,想当然~

总结一些,以下是从其他网站上面得到地一些新知识:

Question:

How do I convert a negative number to an absolute value in Objective-C?

i.e.

-10

becomes

10?

Answer:

Depending on the type of your variable, one of

 abs(int),

 labs(long),

 llabs(long long),

imaxabs(intmax_t),

 fabsf(float),

 fabs(double), or

 fabsl(long double).

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


下面粘上我更正之后地代码,可以试着将代码中的 fabsf 替换成 abs,可以得到截然不同的结果

-(void) setShapes:(NSMutableArray*)shapes { _shapes = shapes; int startX = 360int deltaX = 40int i = 0int distance2center = 0; BOOL flag = YES; for(BYShape *shape in _shapes) {  CCSprite *sprite = [shape getSprite];  int w = sprite.contentSize.width; // 形状的宽度~  int h = sprite.contentSize.height; // 形状的高度~  float rotateRadians = CC_DEGREES_TO_RADIANS(-sprite.rotation);    float absCosTheta = fabsf(cos(rotateRadians));  float absSinTheta = fabsf(sin(rotateRadians));    // w,h只能取得sprite未经任何处理时的高度和宽度,旋转之后,新的宽度和高度需要经过重新计算获得~  // 矩形旋转后的实际宽度和高度可由以下公式获得:  // width = w * abs(cos(theta)) + h * abs(sin(theta))  // height = h * abs(cos(theta)) + w * abs(sin(theta))//  float actualWidth = w * absCosTheta + h * absSinTheta;  float actualHeight = h * absCosTheta + w * absSinTheta;    float transformRatio = (float)TOOL_BAR_HEIGHT / actualHeight; // 比率~    if(transformRatio > 1.0f) { // 如果形状本身的高度就小于 TOOL_BAR_HEIGHT 的话,不进行任何放缩以避免画质降低~   transformRatio = 1.0f;  }    // 保留1位小数//  NSString *reserveOneFloatPart = [NSString stringWithFormat:@"%0.1f", transformRatio];//  transformRatio = [reserveOneFloatPart floatValue];//  NSLog(@"保留1位小数: %.2f", transformRatio);    sprite.position = ccp(startX + deltaX * i, 460);  [sprite runAction:[CCScaleTo actionWithDuration:0.0f scale:transformRatio]];      int spriteHalfWidth = sprite.contentSize.width * transformRatio / 2;  if(i == 0) { // 必须的(之前形状向中间移动的时候对不齐原因就在于没加上这句代码)!!!   // 竟然会出现 transformRatio 和 sprite.scale 不相等的情况,奇葩(可能源于数据还未同步过来)~   _previousShapeHalfWidth = spriteHalfWidth; // 第一个形状的一半宽度  }    if(flag == YES) {   flag = NO;  } else {   distance2center += spriteHalfWidth;   distance2center += TOOL_BAR_INTERVAL; // 两个形状之间的间隔距离~  }  float distance = 160.0f + distance2center;  [sprite runAction:[CCMoveTo actionWithDuration:0.6f position:ccp(distance, 460.0f)]];  distance2center += spriteHalfWidth;  i += 1;  [self addChild:sprite]; }}


           

猜你喜欢

转载自blog.csdn.net/qq_44894420/article/details/89321701