【发布时间】:2017-02-19 00:00:43
【问题描述】:
我目前正在开发一个程序,该程序旨在将八进制分数作为输入并将其转换为十进制分数。到目前为止,我有部分代码可以将小数点前的部分转换为小数点,而不是小数点后的浮点数。我试图使用模数,但由于我的变量是浮点数而没有成功。
有没有办法将小数点后的剩余数字从八进制转换为十进制?我在下面发布了我的代码。任何帮助表示赞赏。谢谢!
int main()
{
float num;
int rem = 0;;
int dec = 0;
int i = 0;
cout << "Please enter a number with a decimal point: ";
cin >> num;
double ohalf = num - (int)num;
int half = num;
while (half != 0)
{
rem = half % 10;
half /= 10; //Converts first have to decimal
dec += rem *= pow(8, i);
i++;
}
cout << dec;
i = -1;
while (ohalf != 0)
{
rem = ohalf *pow(8, i); //Converts second half to decimal. *This is where I am stuck*
i--;
}
cout << rem;
_getch();
return 0;
}
【问题讨论】:
-
我认为将输入处理为
string、split it at the'.'char 会容易得多,在拆分字符串上使用strtol,适当缩放小数部分,然后添加他们变成double。