Sør*_*sen 3 c++ binary decimal base
我做了一个将二进制数转换为十进制数的函数,但是如果我对二进制数进行高位,它只会返回 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 decimal\n";
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";
}
}
Run Code Online (Sandbox Code Playgroud)
我是 C++ 新手,所以我不明白这一点......:/
小智 6
这是你在这里进行的一个很酷的程序......这是我为你的问题找到的可能解决方案......
/* 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;
}
Run Code Online (Sandbox Code Playgroud)
这就是我认为你正在拍摄的。您可以通过从 切换到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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38530 次 |
| 最近记录: |