C++基数 10 到基数 2 的逻辑错误
C++ base 10 to base 2 logic error
我正在做一个基本程序,将数字从基数 10 转换为基数 2。我得到了这个代码:
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
int num=0, coc=0, res=0, div=0;
printf ("Write a base 10 numbern");
scanf ("%d", &num);
div=num%2;
printf ("The base 2 value is:n");
if(div==1)
{
coc=num/2;
res=num%2;
while(coc>=1)
{
printf ("%d", res);
res=coc%2;
coc=coc/2;
}
if(coc<1)
{
printf ("1");
}
}
else
{
printf ("1");
coc=num/2;
res=num%2;
while(coc>=1)
{
printf ("%d", res);
res=coc%2;
coc=coc/2;
}
}
printf ("n");
system ("PAUSE");
return EXIT_SUCCESS;
}
某些数字一切都很好,但是,如果我尝试将数字 11 转换为基数 2,我会得到 1101,如果我尝试 56,我会得到100011......我知道这是一个逻辑问题,我仅限于基本的算法和函数:(......有什么想法吗?
你可以使用它,它更简单,更干净:。使用<algorithm>
中的std::reverse
来反转结果。
#include <algorithm>
#include <string>
using namespace std;
string DecToBin(int number)
{
string result = "";
do
{
if ( (number & 1) == 0 )
result += "0";
else
result += "1";
number >>= 1;
} while ( number );
reverse(result.begin(), result.end());
return result;
}
然而,甚至更干净的版本可能是:
#include<bitset>
void binary(int i) {
std::bitset<8*sizeof(int)> b = i;
std::string s = b.to_string<char>();
printf("n%s",s.c_str());
}
使用上述,结果
binary(11);
binary(56);
是
00000000000000000000000000001011
00000000000000000000000000111000
甚至更好:
#include <iostream>
void binary(int i) {
std::bitset<8*sizeof(int)> b = i;//assume 8-bit byte,Stroustrup "C++..."&22.2
std::cout<<b;
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 错误:“类”类型不是“类”的直接基数
- C++基数 10 到基数 2 的逻辑错误