我做了一个将二进制数字转换为小数的函数,但是如果我对二进制数字取高,它只会返回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";
}
}
我是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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句