2013-12-11 24 views
-2

我有一個數據類型爲CGPoint的變量,名爲endPosition。當endPosition在if語句中獲取它的值時,它返回這個瘋狂的值:結束位置:{1.6347776e-33,1.4012985e-45}如果聲明:CGPoint返回奇怪的值

1.例如:

if ([touch view] != background) 
    { 
     CGPoint location = [touch locationInView:self.view]; 

     CGPoint endPosition; 

     if([touch view] == circle){ 
      CGPoint endPosition = {462.5, 98.5}; 
     } 

     CGFloat xDist = (endPosition.x - location.x); 
     CGFloat yDist = (endPosition.y - location.y); 

     CGFloat distance = sqrt((xDist * xDist) + (yDist * yDist)); 

     NSLog(@"End Position: %@", NSStringFromCGPoint(endPosition)); 
    } 

當CGPoint終端位置不是內部這個if語句,我得到的權值:結束位置:{462.5,98.5}

2 。例如:

if ([touch view] != background) 
    { 
     CGPoint location = [touch locationInView:self.view]; 

     CGPoint endPosition = {462.5, 98.5}; 

     CGFloat xDist = (endPosition.x - location.x); 
     CGFloat yDist = (endPosition.y - location.y); 

     CGFloat distance = sqrt((xDist * xDist) + (yDist * yDist)); 

     NSLog(@"End Position: %@", NSStringFromCGPoint(endPosition)); 
    } 

任何人都可以t我該怎麼辦?我需要這個if語句:)提前致謝。

+0

你進入'if'? – nhgrif

回答

2

這是因爲在第一種情況下,如果[touch view] != circle沒有爲endPoint設置值。

在這種情況下,你的變量是未初始化的,你會得到一個恰好在內存中的隨機值。您必須處理另一個案例(else),或者在聲明變量時將其初始化爲某個值,例如CGPointZero

4

在你的例子1中,你永遠不會初始化endPosition的值。這是因爲在'if'語句(if([touch view] == circle){)中,您正在定義一個名爲endPosition的新變量,它取代了該範圍中的另一個變量。無論如何,你應該初始化endPositionCGPointZero

0
CGPoint endPosition; //This is a declaration of a of new stack variable of name "endPosition" 

    if([touch view] == circle){ 
     CGPoint endPosition = {462.5, 98.5}; //...AND this is a declaration of another variable 
    } 

您想從第二行中刪除CGPoint。

此外,由於您的CGPoint從未初始化,因此它不一定會具有非垃圾值。你可以添加一個else塊,並把endPosition = CGPointZero放在那裏,或者你可以在第一行做到這一點。編輯:另外{462.5,98.5}是錯誤的大小(2雙),{462.5f,98.5f}是2浮點數,但你應該堅持CGPointMake並避免'複雜'文字。

+0

嗨瑞安,這很有道理。但是當我嘗試這樣做時,像這樣:CGPoint sp = CGPointZero; ([touch view] == circle){ \t sp = {462.5,98.5}; //期望的表達式 }我得到這個錯誤的預期表達式? – thar

+0

嘗試將{462.5,98.5}轉換爲CGPointMake(462.5f,98.5f) –

0

解決方案:

CGPoint endPosition = CGPointZero; 

    if([touch view] == circle){ 
     endPosition = CGPointMake(462.5, 98.5); 
    }