通过递归计算模数而不使用模除法

时间:2017-11-16 23:25:51

标签: c++ function recursion modulus

我正在为类项目的递归函数做一个问题。我试图编写一个使用递归函数的程序,该函数计算模数而不实际使用模数运算符。我试图使用参考参数,因为我认为这是最简单的方法,但是我的程序没有按预期运行。

//Michael Hery
//COP 2001
//11/15/2017
//Recursive Modulus

#include <iostream>
#include <iomanip>

using namespace std;

int recursiveMod(int &, int);

int main()
{
    int num;
    int den;
    int displayNum;
    int total;

    cout << "Please input the numerator (an integer) >> ";
    cin >> num;
    while (num < 0)
    {
        cout << "Integer must be greater than or equal to zero. >> ";
        cin >> num;
    }
    displayNum = num;
    cout << "Please input the denominator (an integer) >> ";
    cin >> den;
    while (den <= 0)
    {
        cout << "Integer must be greater than zero. >> ";
        cin >> den;
    }
    cout << "You have entered " << num << " % " << den << endl;

    total = recursiveMod(num, den);

    cout << "Modulus result: " << displayNum << " % " << den << " = " << total << endl;

    system("PAUSE");
    return 0;
}

int recursiveMod(int &num, int den)
{
    if (num == 0)
        return 0;

    num = num - den;

    if ((num - den) > den)
    {
        recursiveMod(num, den);
    }
    return num;
}

3 个答案:

答案 0 :(得分:0)

您的代码有两个错误。首先,您需要包含cstdlib for system(“pause”)才能工作。

#include <cstdlib>

其次,在你的

int recusive mod(int &num, int den)

条件应为num>必须放置书房和返回。

if (num > den)
    {
        return recursiveMod(num, den);
    }

答案 1 :(得分:0)

问题在于这一行:

 if ((num - den) > den)

例如,如果num为4且den为3,则4-3为1且1不大于3,因此您将返回4.您想要的是

 if (num > den)

答案 2 :(得分:0)

试试这个:

int recursiveMod(int num, int den)
{
    if (num < 0) return recursiveMod(num + den, den);

    // Don't forget the case of num = 2 and den = 7
    if (num < den) return num;

    return recursiveMod(num - den, den);
}