减法不起作用

时间:2015-02-12 01:31:14

标签: objective-c operators

以下代码不起作用(位于touchesBegan

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];

NSUInteger a = touchLocation.y;
NSUInteger b = touchLocation.x;
NSUInteger c = _player.center.y;
NSUInteger d = _player.center.x;

NSLog(@"%lu", (unsigned long) b);
NSLog(@"%lu", (unsigned long) a);
NSLog(@"%lu", (unsigned long) d);
NSLog(@"%lu", (unsigned long) c);

int offSetY = a - c;
int offSetX = b - d;
float slope = (offSetY/offSetX);

NSLog(@"%lu", (unsigned long) offSetX);
NSLog(@"%lu", (unsigned long) offSetY);
NSLog(@"%f", slope);

那是75%的真实。当我点击屏幕的右上方象限时,每个变量的结果都很好,但是offSetX不在图表中(通常超过1800000000或更少)。谁能帮我吗?我不明白为什么会出错。

1 个答案:

答案 0 :(得分:2)

为什么要转换为NSUInteger来计算斜率?请改用CGFloat

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];

CGPoint playerPoint = CGPointMake(100, 100);

CGFloat a = touchLocation.y;
CGFloat b = touchLocation.x;
CGFloat c = playerPoint.y;
CGFloat d = playerPoint.x;

NSLog(@"%f", b);
NSLog(@"%f", a);
NSLog(@"%f", d);
NSLog(@"%f", c);

CGFloat offSetY = a - c;
CGFloat offSetX = b - d;
CGFloat slope = (offSetY/offSetX);

NSLog(@"%f", offSetX);
NSLog(@"%f", offSetY);
NSLog(@"%f", slope);