C 如何使用函数上一次调用的结果作为下一次调用的隐含参数?
我是C的初学者,我刚刚写了一个ftn,它消耗两个数字并返回它们的gcd。现在我在想,如果只使用一个数字,如何使用指针找到gcd。谁能告诉我有没有办法?ThxC 如何使用函数上一次调用的结果作为下一次调用的隐含参数?,c,C,我是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(fr
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))
在函数内部使用静态变量,而不使用任何指针
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
的地址。您的要求是指向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];
}
嗯?
GCD(n,n)
当然是n
您是否正在尝试获取一系列数字的GCD?如果您解释您想要这样做的原因,可能会有所帮助。这似乎很奇怪,因为GCD的数学定义需要两个数字。@代码大师它实际上需要两个数字“a”和“b”。“a”是gcd ftn的消耗量。“b”是上一次调用的结果。@为什么您希望GCD函数只“使用”一个数字?GCD不是只使用一个数字吗?为什么int gcd=gcd(n,内部);这里使用两个数字?只需传递n
的地址并在函数中取消引用它。@是的,我忘了重命名函数,gcd()inside是计算实际gcd的函数。internal=n;在if(内部==-1)之后才应该出现。此外,如果将“internal”重命名为“previousResult”,OP可能会更清楚。