简体   繁体   English

我一直在尝试编写一个程序来将十进制转换为二进制,我不知道我的代码有什么问题? 我正在使用代码块

[英]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.你在整个代码中疯狂地混合了doubleint 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.

相关问题 不知道这段代码有什么问题? - I don't know what's going wrong with this code? 我在 C 二进制搜索代码中做错了什么? - What am I doing wrong in my C binary search code? 有人能发现我代码中的错误吗? 我不知道我错过了什么部分,我搞砸了什么 - Can someone spot the errors in my code? I don't know what part am I missing and what I messed up 我正在尝试将C代码转换为Mathematica代码,我在做什么错? - I am trying to convert C code to Mathematica code, what am i doing wrong? 我编写了一个 C 程序来在十进制、十六进制和二进制之间进行转换 - I have written a C program to convert between decimal, hex and binary 用 C 编写代码以将 Decimal 转换为任何基数 我哪里出错了 - Write code in C to convert Decimal to any base Where am I going wrong 我不知道我做错了什么。 我认为我的条件是正确的 - I don't know what I'm doing wrong. I think my condition is right 对于我的C作业,我不了解使用重定向来测试程序意味着什么? - For my C assignment, I am don't understand what it means by using redirection to test the program? 我不知道我对这个数组做错了什么 - I don't know what I'm doing wrong with this Array 我不知道为什么我的代码出错了。 c语言,字符串迭代 - I don't know why I got it wrong in my code. c language, string iterations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM