【问题标题】:C++ convert binary to decimal, octalC++ 将二进制转换为十进制、八进制
【发布时间】:2025-12-28 17:50:12
【问题描述】:

请帮助我调试下面的代码。 我想使用将二进制数转换为十进制或八进制的函数来生成代码。 我在 switch 语句中不断收到错误“函数调用中的参数太少”。

#include <iostream.> 

long int menu();
long int toDeci(long int);
long int toOct(long int);

using namespace std;

int main () 
{
int convert=menu();

switch (convert)
{
case(0):
    toDeci();
    break;
case(1):
    toOct();
    break;
    }
return 0;
}
long int menu()
{
int convert;
cout<<"Enter your choice of conversion: "<<endl;
cout<<"0-Binary to Decimal"<<endl;
cout<<"1-Binary to Octal"<<endl;
cin>>convert;
return convert;
}

long int toDeci(long int)
{

long bin, dec=0, rem, num, base =1;

cout<<"Enter the binary number (0s and 1s): ";
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 dec;
}

long int toOct(long int)
{
long int binnum, rem, quot;
int octnum[100], i=1, j;
cout<<"Enter the binary number: ";
cin>>binnum;

while(quot!=0)
{
    octnum[i++]=quot%8;
    quot=quot/8;
}

cout<<"Equivalent octal value of "<<binnum<<" :"<<endl;
    for(j=i-1; j>0; j--)
    {
        cout<<octnum[j];
    }

}

【问题讨论】:

  • 除非它不会编译,所以调试器毫无意义。 toDeci() 和 toOct() 采用 long int 参数,您没有向它们传递任何东西
  • 在 case(0) 下你传递给 toDeci 的参数有多少?需要多少个?
  • long int toOct(long int) 这样的东西完全没有意义,数字就是数字,文本表示就是文本表示。
  • 您应该使用字符串来读取基数 2 的数字。
  • 这里有一些关于conversion的有用信息:std::dec, std::hex, std::octbin 可能被std::bitset 覆盖。再说一遍:数字就是数字,如何表示这些是另一回事。

标签: c++ function


【解决方案1】:

我想使用将二进制数转换为十进制或八进制数的函数来生成代码。

没有像将 二进制数转换为十进制或八进制数这样的事情 基于数字表示为

long int toDeci(long int);
long int toOct(long int);

这样的函数对于任何语义解释都是完全没有意义的。

数字就是数字,其文本表示可以是十进制十六进制八进制或二进制格式:

dec 42
hex 0x2A
oct 052
bin 101010

long int 数据类型中仍然是相同的数字。


使用 c++ 标准I/O manipulators 使您能够从它们的文本表示形式转换这些格式。

【讨论】:

    【解决方案2】:

    我不确定我是否理解您要执行的操作。这是一个可能对您有所帮助的示例 (demo):

    #include <iostream>
    
    int main()
    {
      using namespace std;
    
      // 64 bits, at most, plus null terminator
      const int max_size = 64 + 1;
      char b[max_size];
    
      //
      cin.getline( b, max_size );
    
      // radix 2 string to int64_t
      uint64_t i = 0;
      for ( const char* p = b; *p && *p == '0' || *p == '1'; ++p )
      {
        i <<= 1; 
        i += *p - '0';
      }
    
      // display
      cout << "decimal: " << i << endl;
      cout << hex << "hexa: " << i << endl;
      cout << oct << "octa: " << i << endl;
    
      return 0;
    }
    

    【讨论】: