2011-12-12 68 views
0

我剛剛開始編程,對於我的第一個項目,我決定編寫一個程序,用於在c中使用歐幾里得除法算法找到最大公約數。在歐幾里德劃分算法中保存步驟

現在,我想擴展問題以節省間歇性商數,餘數,分紅和除數,以便我可以使用它們。

我的想法是,我可以添加一些內部循環,將四個變量的每一個放入數組的一行,然後爲循環的下一次迭代啓動一個新行。

這是我到目前爲止。

#import <Foundation/Foundation.h> 

int main (int argc, const char * argv[]) 
{ 

    NSAutoreleasePool * pool =[[NSAutoreleasePool alloc]init]; 
    NSMutableArray * numberSaver=[[NSMutableArray alloc] init]; 
    NSNumber * q; 
    NSNumber * end; 
    NSNumber * or; 
    NSNumber * rem; 

    int a,b, divisor, dividend, quotient, remainder, temp, gcd, row; 

    //get the two numbers 
    NSLog(@"of which 2 numbers whould you like the GCD?"); 
    scanf("%u%u", &a,&b); 

    //make the bigger number the dividend, smaller divisor 

    if (a>b) { 
     dividend=a; 
     divisor=b; 
    } else { 
     dividend=b; 
     divisor=a; 
    } 

    remainder=1; 
    row=0; 
    while (remainder !=0) { 

     quotient=1; 
     temp=divisor; 

     while (temp<dividend) { 
      temp+=divisor; 
      ++quotient; 
     } 
     q=[NSNumber numberWithInt:quotient]; 
     end=[NSNumber numberWithInt: dividend]; 
     or=[NSNumber numberWithInt: divisor]; 
     //set NSNumber objects q, end, or to the integer values at quotient dividend and divisor 

     gcd=divisor; 
     //This is so that we can save divisor to be the GCD and not change it to 0 before it is printed 
     remainder=quotient*divisor - dividend; 
     rem=[NSNumber numberWithInt:remainder]; 
     //point to the remainder as an object 

     dividend= divisor; 
     divisor= remainder; 
     //Get dividend and divisor ready for the next loop 

     //I'd like to start adding the newly created NSNumbers to numberSaver here 
     [numberSaver addObject:quotient atIndex:row:0]; 
    } 
    NSLog(@"gcd= %u",gcd); 

    [pool drain] ; 

    return 0; 
} 

回答

0

我建議創建一個具有循環的每個迭代一個可變的字典中,加入所有的數字到後,把它放到「主」陣:

while (remainder !=0) { 

    // Each time through the loop, a new dictionary is created and put 
    // into iterationDict; you can then add objects to it. 
    NSMutableDictionary * iterationDict = [NSMutableDictionary dictionary]; 

    // ... 

    q=[NSNumber numberWithInt:quotient]; 
    end=[NSNumber numberWithInt: dividend]; 
    or=[NSNumber numberWithInt: divisor]; 

    [iterationDict setObject:q forKey:@"quotient"]; 
    [iterationDict setObject:end forKey:@"dividend"]; 
    [iterationDict setObject:or forKey:@"divisor"]; 

    // etc. 
    [numberSaver addObject:iterationDict]; 
} 

存放這些東西在字典而不是陣列中意味着您不必記住您添加它們的訂單divisordividend之前,e ..g)。相反,您可以通過密鑰訪問它們。稍後,您可以獲得陣列中任何給定迭代的值:

NSUInteger iteration = 3; 
NSNumber * quotient = [[numberSaver objectAtIndex:iteration] objectForKey:@"quotient"]; 

請評論是否有任何需要說明的內容。

+0

謝謝,效果很好。如果我正在編寫更多代碼,如何在不知道已完成多少次迭代的情況下訪問最後一次迭代? – chartman

+0

@User:數組中的最後一個對象位於'num_objects_in_array - 1'中,所以你可以這樣做:'[numberSaver objectAtIndex:[numbersaver count] - 1]' –