C++:二进制到十进制w/转换过程的外观
C++: Binary to Decimal w/ Appearance of the Conversion Process
我试图制作一个将二进制转换为十进制的程序,但需要显示转换的过程
输入二进制数字:10110
1*(2^4(+1*(2^2(+1*
10110的十进制等价物是:22
但相反,循环中间的计数器值没有降低,导致了这种
样本图像
这是我当前的代码
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
int bin, dec = 0, remainder, num, base = 1,counter=0,counter2=0, constnum;
cout << "Enter the binary number: ";
cin >> num;
bin = num;
constnum = num;
while(bin > 0)
{
bin=bin/10;
counter2++;
}
while (num > 0)
{
if (num % 10 == 1) {
cout << " 1*(2^" << counter2 << ") +";
counter2--;
}
else if(num % 10 == 0) {
counter2--;
}
remainder = num % 10; //get the last digit of the input
dec = dec + remainder * base;
base = base * 2;
num = num / 10;
}
cout << "nThe decimal equivalent of " << constnum << " : " << dec << endl;
return 0;
}
只需使用一个位集:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<32> val;
std::cin >> val;
std::cout << val.to_ulong() << "n";
}
您应该按照升序而不是后代来编写过程,这是为了匹配您的算法,它是按照升序
所以,在你的最后一段时间,而不是这个:
if (num % 10 == 1) {
cout << " 1*(2^" << counter2 << ") +";
counter2--;
}
else if(num % 10 == 0) {
counter2--;
}
你应该这样做:
if (num % 10 == 1) {
cout << " 1*(2^" << counter << ") +";
counter++;
}
else if(num % 10 == 0) {
counter++;
}
此外,如果你遵循我的建议,你可以删除你的第一个时间:
while(bin > 0)
{
bin=bin/10;
counter2++;
}
因为不再需要
如前所述,您正在以不同的顺序计算和显示结果。我建议您存储结果,稍后再显示。类似于:
#include <sstream>
....
int pos = 0;
string res;
while (num > 0) {
if (num % 10 == 1) {
stringstream out;
out << "1*(2^" << pos << ") + ";
res = out.str() + res;
}
remainder = num % 10; //get the last digit of the input
dec = dec + remainder * base;
base = base * 2;
num = num / 10;
pos++;
}
int len = res.length();
// to remove the last '+'
if (len >= 3) {
res = res.substr(0, len - 3);
}
cout << res;
相关文章:
- 防止主数据类型C++的隐式转换
- 递归函数计算序列中的平方和(并输出过程)
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 执行具有转换错误的过程
- C++:二进制到十进制w/转换过程的外观
- 将类转换为过程 API C++:替换成员变量的常用方法?
- 在代码优化过程中,C++11编译器是否会在可能的情况下将局部变量转换为右值
- 在比较过程中C++布尔值是否转换为整数
- 字符串字符是统一码吗?转换过程中会发生什么
- 复制构造函数是如何在从类类型到类类型的类型转换过程中引发的
- 如何在初始化过程中将C中的char转换为int
- c++中向下转换过程中的内存布局
- 在c++中将字符串转换为字符没有完整的过程
- 在递归函数中,c++基转换过程中意外输出到屏幕
- 向下类型转换过程
- 在计算过程中将int类型转换为long long的优点是什么?
- 为什么指针在函数转换过程中会自行更改