c++ - 如何使用递归计算从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 时我将如何计算赔率?我知道递归函数必须调用自己
解决方案
虽然到目前为止您给出的答案确实为您的具体情况产生了正确的答案,但我认为它们并没有真正显示出递归。相反,他们使用你的问题的细节来走捷径,考虑到你的问题听起来很家庭作业,这有点错过了重点。
递归的基本点是你有一个基本情况很容易解决的问题,并且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”数字添加到参数中并保持不变到最后)。
推荐阅读
- javascript - 为什么 Apollo 的 `useQuery` 在给定相同查询的情况下没有返回一致或正确的结果?
- lua - Roblox leaderstats 不会显示
- javascript - 如何使用条件导入编写在浏览器和 Node 中都可以使用的 ESM 模块
- c# - .Net DLL 引用错误(强名称符号后)
- vb.net - 从文件中读取字节,但它们可能位于文件中的任何位置(VB.NET)
- c# - 将构造函数参数传递给 Unity-Container-Registration
- algorithm - Word break (leetcode #139) Python 解决方案超时——记忆化不起作用?
- swift - 在 Swift Storyboard 中设置自动布局时,为什么会出现 NSInternalInconsistencyException?
- python - MetPy suface_based_cape_cin 返回带有单位的错误
- javascript - 格式化要在 Vue.js 组件中使用的 laravel 路由字符串