如何解决为什么我的函数代码中存在一个模棱两可的地方,即以十进制n的二进制表示形式计算1的数量
我需要一个函数来计算十进制n的二进制表示形式中的1。但是当我编译它时,它会出现以下错误enter image description here
这是我的代码
int countBits(unsigned int n){
if(n%2 == 0){
return countBits(n/2);
}else if(n%2 != 0){
return 1 + countBits(floor(n/2));
}else if(n == 1){
return 1;
}else{
return 0;
}
}
这就是我在main中的称呼方式
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
void outputBinary(unsigned int x);
int countBits(int n);
int main(){
int a = 21;
int b = countBits(a);
cout << b << endl;
return 0;
}
如何修复?谢谢
解决方法
您已经用两种不同的方式定义和声明了countBits
。在您的第一个代码段中,您有int countBits(unsigned int n)
(带有 unsigned int 参数),但是,在您的第二个代码段中,您将“转发声明”指定为int countBits(int n);
-带有(签名)int
。
编译器不知道在您的调用中使用哪种形式。
您应该修改代码,以使两个函数签名相同-最有可能的是,应更改声明(在第二个代码段中)以匹配第一个,因此将其更改为:int countBits(unsigned int n);
。 / p>
此外,您的countBits
函数将不断调用自身,因为前两个if
/ else if
块之一将 始终 是真实的(即使给定的参数是0
或1
)-这将最终导致程序崩溃。要解决此问题,请首先测试0
或1
:
int countBits(unsigned int n)
{
if (n == 1) {
return 1;
}
else if (n == 0) {
return 0;
}
else if (n % 2 == 0) {
return countBits(n / 2);
}
else {// if (n % 2 != 0) {
return 1 + countBits(floor(n / 2));
}
}
此外,您可以将前两个测试“合并”为一个:
int countBits(unsigned int n)
{
if (n < 2) {
return n;
}
else if (n % 2 == 0) {
return countBits(n / 2);
}
else {
return 1 + countBits(n / 2); // don't need "floor" for integer division
}
}
随时要求进一步的澄清和/或解释。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。