C++ 函数,用于检查每个位是否为 0 或 1
c++ function that checks each individual bit for 0 or 1
我在这项作业中遇到了问题。我昨天和今天都在努力,但没有运气。
说明: 该函数扫描单词,从位开始位开始,向更有效的位,直到找到第一个零 (0( 位。
接下来,该函数返回找到的位的索引。如果startingBit处的位已经是所寻求的,则返回startingBit。
如果未找到位,则返回 UINT MAX(在 climits 中定义(。这是我的代码。
#include <bitset>
#include <climits>
extern const int N = sizeof(int) * CHAR_BIT; // # of bits in an int
unsigned int scan0(unsigned int word, unsigned int startingBit)
{
extern const int N;
unsigned int currentBit = UINT_MAX; // -1 means UINT_MAX, if you see its definition that is
for (currentBit = startingBit; currentBit < static_cast<unsigned int>(N); currentBit += 1)
{
getBits(word, currentBit);
}
if (currentBit <<= 0)
{
return currentBit;
}
if (currentBit != 0)
{
return UNIT_MAX;
}
}
int main()
{
unsigned int i, x;
while (cin >> x)
{
cout << setw(10) << x << " base 10 = " << bitset<N>(x) << " base 2" << endl;
for (i = 0; i < static_cast<unsigned int>(N); ++i)
cout << "scan0(x, " << setw(2) << i << ") = " << setw(2) << scan0(x, i) << endl;
cout << endl;
}
return EXIT_SUCCESS;
}
我的代码说有一个未定义的 main 引用。
#include <climits>
#include <iostream>
#define setbit( _b ) ( 1 << _b )
unsigned int scan0( unsigned int word, unsigned int bit )
{
while( word & setbit( bit ) ) ++bit;
return( ( bit < ( CHAR_BIT * sizeof( unsigned int ) ) ) ? bit : UINT_MAX );
}
int main( void )
{
std::cout << scan0( 0xFF, 3 ) << std:: endl;
std::cout << scan0( ~0x0000, 0 ) << std:: endl;
return( 0 );
}
在我的手机上没有编译器,但是您的代码在该extern中存在错误。起初我以为你是在想说函数存在于其他文件中。但是,如果它们在同一个文件中,你为什么要让它成为extern?Extern有点像说"嘿,任何能看到这个值的人都可以使用这个值,但它的记忆实际上存在于不同的翻译单元中"。您不能声明 extern 变量并在同一声明中设置它;这样做是没有意义的。我建议查看extern C关键字的定义。
相关文章:
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 函数是否可以访问传递给main()的参数
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 在这种情况下,java对象是否可以调用本机函数
- 检查函数返回类型是否与STL容器类型值相同
- 根据某个函数是否存在启用模板
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 无论如何,我可以确定构造函数是否存在吗?
- 是否可以将函数导入命名空间,但不能导出它?
- 返回指向对象的指针的函数调用是否为 prvalue?
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 是否有任何建议来统一函数类型限定符并简化可恶的函数类型?
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本