C++ 函数,用于检查每个位是否为 0 或 1

c++ function that checks each individual bit for 0 or 1

本文关键字:是否 函数 用于 检查 C++      更新时间:2023-10-16

我在这项作业中遇到了问题。我昨天和今天都在努力,但没有运气。

说明: 该函数扫描单词,从位开始位开始,向更有效的位,直到找到第一个零 (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关键字的定义。

相关文章: