将c风格的程序转换为c++
Converting a c style program to a c++
我有这个C风格的程序:
void showOneByteBinaryNumber( char c ) {
for ( int i = 128; i >=1; i >>= 1 ) {
// Fixed Typo - Replaced a ; with the correct {
if ( c & i ) {
printf( "1" );
} else {
printf( "0" );
}
}
}
int main() {
for ( int i = 0; i < 256; i++ ) {
printf( "%3d = ", i );
showOneByteBinaryNumber( i );
printf( "n" );
}
return 0;
}
然后将程序修改为:
void showOneByteBinaryNumber( char c ) {
for ( int i = 128; i >= 1; i >>= 1 ) {
if ( c & i ) {
std::cout << 1;
}
else {
std::cout << 0;
}
}
}
int main() {
for ( int i = 0; i < 256; i++ ) {
std::cout << "%3d = " << i;
showOneByteBinaryNumber( i );
std::cout << "n";
}
return 0;
}
我应该期望看到二进制值的表从0增加到255,但是当我尝试使用std::cout
将其转换为c++等效版本时,我在输出中得到的其他数字不是0或1。
我不确定罪魁祸首是在改变的函数内还是在main中的for循环内。我不知道如何改变printf()
"%3d"
的参数;对std::cout
是RamandepPunia为我提供了正确的答案!
在这行代码中:
printf( "%3d", i );
我试图用
替换它std::cout << "%3d = " << i; // I did initially try std::setw( 3 ) but was giving wrong results;
std::cout << std::setw(3) << " = " << i;
他的注释代码:
std::cout << std::setw(3) << i << " = ";
是我正在寻找的,现在程序给了我正确的结果!
编辑
在我得到它的工作后,我确实修改了我的函数如下:
void showOneByteBinaryNumber( char c ) {
for ( int i = 128; i >= 1; i >>= 1 ) {
std::cout << ( (c & i) ? 1 : 0);
}
}
然而,David C. Rankin也给我看了这个版本
void showOneByteBinaryNumber( char c ) {
for ( int i = 1 << 7; i; i >>= 1 ) {
c & i ? std::cout << 1 : std::cout << 0;
}
}
相关文章:
- C++实用程序::转换在静态链接库中不起作用
- 如何将我的小程序转换为用于项目的函数?
- 将通用Windows应用程序转换为VisualStudio 2019上的常规应用程序
- 如何将我的程序转换为.dll文件并使用rundll32.exe在cmd中运行它?
- 将 C 程序转换为具有大量字符* 和无符号字符转换错误的C++
- 将视觉C 媒体基础捕获应用程序转换为C 构建器
- Qt 创建器中的实用程序::转换::to_string_t中的链接错误
- 将Parralel CUDA程序转换为顺序运行
- Pthreads - 将顺序程序转换为并行程序
- 尝试将工作python程序转换为C++但不起作用
- 将带有 std::cout C++程序转换为 NCurses / CDK
- 面向对象设计-将C应用程序转换为C++
- 将带有迭代器的C++程序转换为 Boost MPI 并行程序
- 可视化如何将项目 win32 控制台应用程序转换为C++ Windows 窗体
- 如何使用 openMP 将顺序程序转换为并行程序
- 将C++程序转换为使用 GMP
- 如何将 C 程序转换为类
- 将命令行参数程序转换为菜单驱动程序
- 将C++程序转换为 C#
- 必须执行哪些操作才能将程序转换为强大的 OpenMP 感知版本