这是我的代码,我无法弄清楚为什么当main()中的确切代码产生正确答案时它不能作为函数工作。赋值是将二进制数转换为十进制数。
#include <iostream>
#include <cstdlib>
#include "std_lib_facilities.h"
using namespace std;
int binaryCon(int biNum);
int main()
{
int num, bin, Bnum;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
Bnum = binaryCon(num);
cout << "The decimal equivalent of " << bin << " : " << Bnum << endl;
}
int binaryCon(int biNum)
{
long dec = 0, rem = 0, base = 1;
enter code here`while (biNum > 0)
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
return biNum;
}
答案 0 :(得分:0)
由于您未在while循环中使用{
和}
,因此可能会进入无限循环。因为它只适用于这一行
while (biNum > 0)
rem = biNum % 10; // running this line infinite as `biNum > 0`
使用
while (biNum > 0){
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}
答案 1 :(得分:0)
也许这个?
while (biNum > 0)
{
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}
答案 2 :(得分:0)
更正后的代码:
#include <iostream>
#include <cstdlib>
using namespace std;
int binaryCon(int biNum);
int main()
{
int num, bin, Bnum;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
Bnum = binaryCon(num);
cout << "The decimal equivalent of " << bin << " : " << Bnum << endl;
getchar();
return 0;
}
int binaryCon(int biNum)
{
long dec = 0, rem = 0, base = 1;
while (biNum > 0){
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}
return dec;
}
答案 3 :(得分:0)
int main()或int main(int argc,char ** argv)必须返回一个值。如果返回0则表示代码没有问题。另一个数字1,2等表示存在错误。(返回的数字是错误编号)