C++二进制到十进制

C++ Binary to decimal?

本文关键字:十进制 二进制 C++      更新时间:2023-10-16

我做了一个将二进制数转换为小数的函数,但是如果我在二进制数上达到高位,它只会返回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。