我是一个学习C语言的新手,曾试图创建一个程序,提供2个输入数字的最高公约数。但是,在成功编译之后,在向scanf提示符输入数据之后,我会得到标题为error的错误。我试着永远解决它,但做不到。请忽略双斜线。

//Declare external libraries and function calls //
#include <stdio.h>
void gcdFunction (int *variable1, int *variable2);

// Main Program//
int main(void)
{
    int firstNumber = 0, secondNumber = 0;
    printf("Please enter first value \n");
    scanf("%d", &firstNumber);
    printf("Please enter second value \n");
    scanf("%d", &secondNumber);
//Call function passing 2 address parameters //
    gcdFunction(&firstNumber, &secondNumber);
}

// Call function, passing parameters as pointers //
void gcdFunction(int *variable1, int *variable2)
{
    int i, z;
    while (i != 0)
    {
        i = *variable2;
        *variable2 = *variable1 % *variable2;
        *variable1 = i;
    }
    z = *variable1;
    printf("\nThe GCD of the two values entered is: %d", z);
}

最佳答案

问题就在这个循环中:

while (i !=0){
    i = *variable2;
    *variable2 = *variable1 % *variable2;
    *variable1 = i;
}

这里,如果*variable2变为0,它将在下一次迭代中用作模的右侧,因为i是在检查循环条件后设置的。把它改成
while (*variable2 !=0){
    i = *variable2;
    *variable2 = *variable1 % *variable2;
    *variable1 = i;
}

那么错误就不会再发生了。

10-06 05:05