我的C函数出了什么问题?最大公约数和最小公倍数

时间:2017-12-05 23:32:41

标签: c

#include <stdio.h>
#include <stdlib.h>

// Function to find the greatest common divisor
int findGCD(int numberOne, int numberTwo) {

    int i, GCD;

    for (i = 1; i <= numberOne && i <= numberTwo; i++) {
        if (numberOne % i == 0 && numberTwo % i == 0);
    }

    GCD = i;

    return GCD;
}

// Function to find the least common multiple using the GCD function

int findLCM(int numberOne, int numberTwo) {

    int GCD, LCM;

    GCD = findGCD(numberOne, numberTwo);
    LCM = (numberOne * numberTwo) / GCD;

    return LCM;
}

// Main function to output the lcm
void main() {

    int numberOne, numberTwo, LCM;

    printf("Please enter two numbers: ");
    scanf_s("%i %i", &numberOne, &numberTwo);

    LCM = findLCM(numberOne, numberTwo);

    printf("The LCM of %i and %i is %i\n", numberOne, numberTwo, LCM);

    system("pause");
}

1 个答案:

答案 0 :(得分:0)

您的findGCD无法完美地计算GCD。你错放了GCD = i

// Function to find the greatest common divisor
int findGCD(int numberOne, int numberTwo) {

    int i, GCD;

    for (i = 1; i <= numberOne && i <= numberTwo; i++) {
        if (numberOne % i == 0 && numberTwo % i == 0) {
            GCD = i;
        }
    }

    return GCD;
}