C++二进制到十进制
C++ Binary to decimal?
我做了一个将二进制数转换为小数的函数,但是如果我在二进制数上达到高位,它只会返回256???什么原因可能导致这种情况?我正在使用 int 变量。任何帮助将不胜感激
#include <iostream>
using namespace std;
int FromBin (int n)
{
int increment;
int Result;
increment = 1;
Result = 0;
while(n != 0)
{
if (n % 10 == 1){
Result = Result+increment;
n = n-1;
}
n = n/10;
increment = increment*2;
}
cout<<Result;
}
void ToBin(int n)
{
if (n / 2 != 0) {
ToBin(n / 2);
}
cout<<n % 2;
}
int main()
{
int choice;
int n;
cout<<"Choose a function: press 0 for decimals to binary, press 1 for binary to decimaln";
cin>>choice;
if (choice == 0){
cout<<"Enter a number: n";
cin>>n;
ToBin(n);
}
else if (choice == 1){
cout<<"Enter a number: n";
cin>>n;
FromBin(n);
}
else{
cout<<"Invalid input";
}
}
我是C++新手,所以我不明白这一点... :/
这是一个很酷的程序,你在这里开始了...这是我为您的问题找到的可能解决方案......
/* C++ program to convert binary number into decimal */
#include <iostream>
using namespace std;
int main()
{
long bin, dec = 0, rem, num, base = 1;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
while (num > 0)
{
rem = num % 10;
dec = dec + rem * base;
base = base * 2;
num = num / 10;
}
cout << "The decimal equivalent of " << bin << " : " << dec << endl;
return 0;
}
这就是我认为你拍摄的目的。您可以通过从 int
切换到 long
来处理更大的数字。
long fromBin(long n)
{
long factor = 1;
long total = 0;
while (n != 0)
{
total += (n%10) * factor;
n /= 10;
factor *= 2;
}
return total;
}
现场演示
从您的评论中,我可以看到您正在尝试将其用于对于 int 变量来说太大的数字。寻找限制,至于int,我发现最大值是2147483647。
相关文章:
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- C++从二进制转换为十进制数
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- uint8_t同一二进制文件的不同十进制值
- 十进制到二进制转换器 c++
- 如何在C ++中将二进制字符串128位转换为十进制字符串?
- 将二进制转换为十进制,我如何要求用户仅输入二进制
- C++:二进制到十进制w/转换过程的外观
- 如何在C++中将二进制编码十进制转换为 int
- 如何使用链表将负十进制数转换为二进制?
- 十进制,包括负到 32 位二进制转换器
- 输入 1024 后十进制到二进制转换的输出错误?
- 以正确的顺序从十进制转换为二进制
- 二进制反转为十进制数
- 十进制到二进制的实现不能完全适用于我大学的检查器。问题或提示可能是什么
- 如何将值从十进制存储为二进制,使其在 C++ 中将值保存在 6 位
- 使用指数将十进制转换为二进制
- 将40个字节长的数据框从十六进制转换为二进制,然后转换为十进制
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?