C、日志、二进制、数字四。他们不混合
#include <stdio.h>
#include <math.h>
/* converts to binary using logs */
int main()
{
long int decimalNUM = 0, binaryNUM = 0, exponentNUM = 0;
printf("Enter a number to be converted to binary.\t");
scanf("%ld", &decimalNUM);
fflush(stdin);
int origDEC = decimalNUM;
while (decimalNUM > 0)
{
exponentNUM = (log(decimalNUM))/(log(2));
binaryNUM += pow(10, exponentNUM);
decimalNUM -= pow(2, exponentNUM);
}
printf("\nBINARY FORM OF %ld is %ld", origDEC, binaryNUM);
getchar();
return binaryNUM;
}
如果 STDIN 为 4,则返回 99,但它不应该返回。在 IDEONE 上它返回 100。为什么?
编辑似乎任何大于二的偶数都会返回带有九的东西
#include <stdio.h>
#include <math.h>
/* converts to binary using logs */
int main()
{
long int decimalNUM = 0, binaryNUM = 0, exponentNUM = 0;
printf("Enter a number to be converted to binary.\t");
scanf("%ld", &decimalNUM);
fflush(stdin);
int origDEC = decimalNUM;
while (decimalNUM > 0)
{
exponentNUM = (log(decimalNUM))/(log(2));
binaryNUM += pow(10, exponentNUM);
decimalNUM -= pow(2, exponentNUM);
}
printf("\nBINARY FORM OF %ld is %ld", origDEC, binaryNUM);
getchar();
return binaryNUM;
}
If STDIN is 4 it returns 99 and it should not. On IDEONE it returns 100. Why?
EDIT seems that any even number above two returns something with nines in it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像 log 这样的浮点运算并不精确。在我的机器上,这段代码按预期运行(STDIN 上的 4 给出 100)。
实现此目的的一种方法是使用连续的 2 次幂的 mod (%) 运算符。
Floating point operations like log are not exact. On my machine this code runs as expected (4 on STDIN gives 100).
One way you could do this, is by using the mod (%) operator with successive powers of two.
工作正常: http://ideone.com/PPZG5
正如评论中提到的,你的方法真的很奇怪。
通用的 n 进制转换例程如下所示:
Works fine : http://ideone.com/PPZG5
As mentioned in the comments, your approach is really strange.
A general base-n conversion routine looks like: