C++将二进制转换为十进制,八进制
问题描述:
请帮我调试下面的代码。 我想使用函数将二进制数转换为十进制或八进制。 我一直在switch语句错误“函数调用错误太少参数”。C++将二进制转换为十进制,八进制
#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];
}
}
答
我想以使用函数转换二进制数转换为十进制或八进制代码。
有像转换二进制数转换为十进制或基于数值表示的八进制作为
long int toDeci(long int);
long int toOct(long int);
这样的功能,没有这样的事情是任何语义解释完全荒谬的。
数字是数字和它们的文本表示可以是小数,六角,八进制或二进制格式:
dec 42
hex 0x2A
oct 052
bin 101010
都仍处于long int
数据类型相同的数字。
使用C++标准I/O manipulators使您能够使这些格式转换从他们的文字表述。
答
我不知道我明白你想要做什么。这里有一个例子可以帮助你(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;
}
除了它不会编译,所以调试器是毫无意义的。 toDeci()和toOct()需要一个很长的int参数,并且你没有传递任何东西 – Pemdas
在case(0)下,你传递给toDeci的参数是多少?它需要多少? –
类似'long int toOct(long int)'是完全无意义的,数字是数字,文本表示是文本表示。 –