[英]I have been trying to write a program to convert decimal to binary , I don't know what is wrong with my code ? i am using codeblocks
this is my code , I think something wrong with the shift operator , I used them in embedded software but I don't know if it is ok to use them on normal code , I have written a code to do the same purpose but with the method of adding (2*10^digit) but it seems a lot easier to use shifts-if possible-, please help :这是我的代码,我认为移位运算符有问题,我在嵌入式软件中使用了它们,但我不知道是否可以在普通代码中使用它们,我已经编写了一个代码来实现相同的目的,但是使用添加 (2*10^digit) 的方法,但如果可能的话,使用移位似乎更容易,请帮助:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double find_power(double x);
int main()
{
double bin=00000000, dec , k ;
printf("enter decimal number:\n");
scanf("%d",&dec);
for(;;)
{
k=find_power(dec);
bin|=(1<<k);
dec-=pow(2,k);
if(dec==1)
{
bin|=(1<<0);
break;
}
else if(dec==0)
{
bin&=(~(1<<0));
break;
}
}
printf("%d",bin);
return 0;
}
double find_power(double x)
{
double i=1,j=0;
for(;;)
{
i*=2;
if(x>=i)
{
j++;
}
else if(x<i)
{
break;
}
}
return j;
}
You are wildly mixing double
and int
all over the code.你在整个代码中疯狂地混合了
double
和int
。 You try to read an int
into a double
with scanf, which invokes undefined behavior.您尝试使用 scanf 将
int
读入double
,这会调用未定义的行为。 And then you try to use double
variables together with bitwise operators, which most likely doesn't make any sense.然后您尝试将
double
变量与按位运算符一起使用,这很可能没有任何意义。 You'll want to use an unsigned integer of known size instead.您将需要使用已知大小的无符号整数。
You should enable/listen to compiler warnings.您应该启用/收听编译器警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.