2016-12-25 20 views
0

在下面的代碼中,我想計算循環結束時強度的淨和,但是目標C在NSlog中調用zsum未聲明的變量。我如何計算結束off循環的Sum並將其傳遞到循環外部。objective c在循環外指定數組變量

NSMutableArray *arr = [[NSMutableArray alloc] init]; 
for (int x = 1; x < 20; x++) { 
    double zsum = 0; 
    NSMutableArray *row = [NSMutableArray new]; 
    for (int y = 1; y < 20; y++) { 
     uchar intensity= curFrame.at<uchar>(cvPoint(y, x)); 
     double zebra = double (intensity)/255; 
     zsum+= zebra; 
     [row addObject:[NSNumber numberWithChar:intensity]]; 
    } 

    // NSLog(@"%d", x); 

    //NSLog(@"%f",d); 
    [arr addObject:[NSNumber numberWithInt:zsum]]; 
// [matrix addObject:row]; 
} 
NSLog(@「%f",zsum); 
+0

您試圖訪問for循環範圍外的變量,這就是爲什麼zsum未定義的原因。 – cheesey

+0

如果這是問題,只需在for循環的範圍之上初始化zsum即可。 – cheesey

回答

1

所以移動zsum的decaration外部for循環中,ARR宣佈後和之前的for循環:

NSMutableArray *arr = [[NSMutableArray alloc] init]; 
double zsum = 0; 
for (int x = 1; x < 20; x++) { 
    //The rest of your for loop code goes here. 
} 

在Objective-C,任何時間碼括在大括號({}),它定義了一個新的範圍。在這些大括號內聲明的任何變量只存在於大括號內。當你退出大括號時,變量「超出範圍」並且不再存在。外部作用域中定義的變量對更深層次的作用域可見,但不在外部。

{ 
    int a; 
    { 
    //a is visible 
    int b; 
    //a and b are both visible 
    } 
    //b is no longer visible 
    { 
    //int c 
    //a and c are visible 
    { 
     int d; 
     //a, c, and d are visible 
    } 
    //a and c are visible, d is no longer visible. 
    } 
    //only a is visible 
} 
//None of the vars are visible 

上面的代碼是相當人爲的,但是有效的。你不可能擁有僅限定範圍級別的大括號​​,但可以。更有可能他們會附上塊,如果說明,函數等的主體。