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;
}
謝謝,效果很好。如果我正在編寫更多代碼,如何在不知道已完成多少次迭代的情況下訪問最後一次迭代? – chartman
@User:數組中的最後一個對象位於'num_objects_in_array - 1'中,所以你可以這樣做:'[numberSaver objectAtIndex:[numbersaver count] - 1]' –