【发布时间】: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::oct。 bin 可能被std::bitset 覆盖。再说一遍:数字就是数字,如何表示这些是另一回事。