首页 > 解决方案 > 如何使用递归计算从0到给定数字的奇数?

问题描述

问题要求创建一个递归函数,它将计算从 0 到数字的奇数,因为这是我拥有的代码:

#include <iostream>

int count_odd (int count) {
    if (count % 2 == 0) {
        return count / 2;
    }
    else {
        return count_odd((count/2)+1); // i know this part is wrong
    }

    return count;
}

int main() {
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;

    if (num < 0) {
        std::cout << "Invalid input.\n";
    } else {
        int odd;

        odd = count_odd(num);

        std::cout << "The number of odds from 0 to " << num << " is " << odd << "\n";
    }

    return 0;
}

count_odd 函数中“if”语句的第一部分在输入偶数整数时返回赔率数,但是当输入奇数 int 时我将如何计算赔率?我知道递归函数必须调用自己

标签: c++

解决方案


虽然到目前为止您给出的答案确实为您的具体情况产生了正确的答案,但我认为它们并没有真正显示出递归。相反,他们使用你的问题的细节来走捷径,考虑到你的问题听起来很家庭作业,这有点错过了重点。

递归的基本点是你有一个基本情况很容易解决的问题,并且n+1如果n-1你有n.

在这种情况下,我会选择0作为基本情况,并说它不是奇数(或偶数;0 是特殊的)。这给了我们这个代码:

    if (number == 0)
        return 0;

其次,如果我们知道X所有前面的数字中都有奇数。那么,如果当前数字是奇数,则当前计数为X+1,如果为偶数,则当前计数为X。这给了我们这个:

    if (number % 2 == 0)
        // even
        return countOdd(number - 1);
    else
        // odd
        return countOdd(number - 1) + 1;

然后如果我们把它放在一起,结果是这样的:

#include <iostream>

int countOdd(int number)
{
    if (number == 0)
        return 0;

    if (number % 2 == 0)
        // even
        return countOdd(number - 1);
    else
        // odd
        return countOdd(number - 1) + 1;
}

int main()
{
    int number = 9;
    std::cout << "There are " << countOdd(number) << " odd numbers from 0 to " << number << std::endl;

    return 0;
}

附言。我选择 0 作为基本情况,因为我认为这是最合乎逻辑的选择。如果您必须从 0 到 n 是一个强要求,那么这应该足以让您自己继续反转逻辑(提示:您需要将“count to”数字添加到参数中并保持不变到最后)。


推荐阅读