我是c的编程新手。运行以下代码时,我收到以下错误,并带有一个指向=符号的小箭头:
错误:无法忽略void值,因为它应该是
* gcd = gcd_lcm((factor1%factor2),factor2,gcd,lcm);
我尝试按照在另一篇文章中找到的将值返回到void类型的步骤,但似乎在我的代码中不起作用。有人可以指出我的错误吗?非常感谢。
#include <stdio.h>
void gcd_lcm(int factor1, int factor2, int *gcd, int *lcm);
int main(void)
{
int factor1;
int factor2;
int GCD;
int LCM;
printf("Enter Factor1: ");
scanf(" %d", &factor1);
printf("Enter Factor2: ");
scanf(" %d", &factor2);
gcd_lcm(factor1, factor2, &GCD, &LCM);
printf("The GCD of %d and %d is %d. The LCM is %d\n", factor1, factor2,
GCD, LCM);
return 0;
}
void gcd_lcm(int factor1, int factor2, int *gcd, int *lcm)
{
if (factor2 == 0)
{
*gcd = factor1;
*lcm = (factor1 * factor2) / *gcd;
}
else
{
*gcd = gcd_lcm((factor1 % factor2), factor2, gcd, lcm);
*lcm = (factor1 * factor2) / *gcd;
}
}
我已将代码更改为此,现在可以使用,但是如何?
void gcd_lcm(int factor1, int factor2, int *gcd, int *lcm)
{
if (factor2 == 0)
{
*gcd = factor1;
*lcm = (factor1 * factor2) / *gcd;
}
else
{
gcd_lcm(factor2, (factor1 % factor2), gcd, lcm);
*lcm = (factor1 * factor2) / *gcd;
}
}
答案 0 :(得分:1)
你写了
void gcd_lcm(int factor1, int factor2, int *gcd, int *lcm);
这意味着gcd_lcm
没有返回值。
这里你试图使用它的返回值(它没有):
*gcd = gcd_lcm((factor1 % factor2), factor2, gcd, lcm);
猜测,因为gcd
传递给递归调用,你可以使用:
gcd_lcm((factor1 % factor2), factor2, gcd, lcm);
但如果我没弄错的话,factor2
永远不会改变,所以递归永远不会停止......
答案 1 :(得分:0)
下面:
*gcd = gcd_lcm((factor1 % factor2), factor2, gcd, lcm);
gcd_lcm()
函数没有返回值但是你试图抓住它。