我是C的初学者,我刚写了一个消耗两个数字的ftn并返回它们的gcd。现在我在想如果你只消耗一个数字,你如何找到一个gcd 使用指针。任何人都可以告诉我是否有办法吗? THX。
Example:
gcd(5) = 5 (gcd of 5 and itself)
gcd(10) = 5 (gcd of 10 and 5(from the last call))
gcd (4) = 1 (gcd of 4 and 5(from the last call))
gcd (7) = 1 (gcd of 7 and 1(from the last call))
答案 0 :(得分:1)
在函数内部使用静态变量,不使用任何指针。
int PreviousGcd( int n )
{
static int previous = -1 ; //pick a magic number
if( previous == -1 )
{
previous = n ;
return previous ;
}
else
{
int result = gcd( n , previous ) ;
previous = n ;
return result ;
}
}
如果你真的想要指针,你可以传递n
的地址。
答案 1 :(得分:1)
您的要求是指向int
的指针。但是,指针可能是两个int
s,因此先前计算的结果可以存储在第二个int
中。举例说明:
int input[2] = { 0, 0 };
*input = 5;
printf("%d\n", gcd(input));
*input = 10;
printf("%d\n", gcd(input));
*input = 4;
printf("%d\n", gcd(input));
*input = 7;
printf("%d\n", gcd(input));
int gcd (int *v) {
if (v[1] == 0) v[1] = v[0];
/* ...compute GCD of v[0] and v[1], store result in v[1] */
return v[1];
}