二进制在C为十进制 [英] Binary to decimal in c

查看:131
本文介绍了二进制在C为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的code到二进制转换为十进制数。在我的编译器,分解工作只是罚款数小于1000,超越输出始终是相同的1023任何人有一个想法?

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;//多少十功率有在一些
//(我不使用POW()函数来避免与浮点数麻烦)
INT residu(INT N)
{
    INT I = 0;
    而(N> = 1){
        N = N / 10;
        我++;
    }
    返回我;
}//由数B exponentiating的号码的
INT功率(INT A,INT B){
    INT I;
    中期业绩= 1;
    对于(i = 0; I< B;我++){解析度= A *资源;}
    返回水库;
}//转换数字N
诠释的main()
{
    INT I;    //数转换
    INT N;
    scanf函数(%d个,&安培; N);    //最后的结果小数
    INT RES = 0;
    //我们分解N按降序的10次幂,M是休息
    INT M = 0;    对于(i = 0; I< residu(N);我++){
        //简单的循环看,如果有在N(residu(N)-1-I)的功率,
        //如果是我们增加由二进制分解
        //功率(2 residu(N)-1-I)
        如果(M +电源(10,residu(N)-1-i)的&下; = N)
        {
            M = M +电源(10,residu(N)-1-i)的;
            RES =功率(2 residu(N)-1-I)+资源;
        }
    }
    的printf(%d个\\ N,RES);
}


解决方案

是尝试这个办法:

 的#include<&stdio.h中GT;
INT主要(无效)
{
焦斌; INT DEC = 0;而(斌!='\\ n'){
scanf函数(%C,&安培;斌);
如果(斌=='1')DEC =减速* 2 + 1;
否则,如果(斌=='0')*月= 2; }的printf(%d个\\ N,DEC);返回0;}

I have a simple code to convert binary to decimal numbers. In my compiler, the decomposition works just fine for number less than 1000, beyond the output is always the same 1023. Anybody has an idea ?

#include <stdio.h>
#include <stdlib.h>

// how many power of ten is there in a number 
// (I don't use the pow() function to avoid trouble with floating numbers)
int residu(int N)
{
    int i=0;
    while(N>=1){
        N=N/10;
        i++;
    }
    return i;
}

//exponentiating a number a by a number b
int power(int a, int b){
    int i;
    int res=1;
    for (i=0;i<b;i++){res=a*res;}
    return res;
}

//converting a number N
int main()
{
    int i;

    //the number to convert
    int N;
    scanf("%d",&N);

    //the final decimal result
    int res=0;
    //we decompose N by descending powers of 10, and M is the rest
    int M=0;

    for(i=0;i<residu(N);i++){
        // simple loop to look if there is a power of (residu(N)-1-i) in N, 
        // if yes we increment the binary decomposition by 
        // power(2,residu(N)-1-i)
        if(M+ power(10,residu(N)-1-i) <= N)
        {
            M = M+power(10,residu(N)-1-i);
            res=power(2,residu(N)-1-i)+res;
        }
    }
    printf("%d\n",res);
}

解决方案

Yes try this :

#include <stdio.h>
int main(void) 
{ 
char bin; int dec = 0;

while (bin != '\n') { 
scanf("%c",&bin); 
if (bin == '1') dec = dec * 2 + 1; 
else if (bin == '0') dec *= 2; } 

printf("%d\n", dec); 

return 0;

}

这篇关于二进制在C为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆