C語言十進制轉換二進制八,十六進制。二進制轉十進制。

C語言十進制轉換二進制八,十六進制。code

十進制轉二進制有個計算公式,就是除以2取餘再倒序顯示餘數就是了。能夠根據公式寫。八制進公式也同理。十六進制有點不同,大於9的要轉爲字母。A,B,C,D,E,F。get

#include <stdio.h>
void totwo();
void toeight();
void tosixt();
int main()
{ 
	totwo();
	toeight();
	tosixt();
    return 0;
}
void totwo()
{
	int p,m,n,a[100];
	printf("十進制轉二進制\n");
	printf("輸入十進制數:");
	scanf("%d",&p);
	for(m=0;p>0;m++)
	{
		a[m]=p%2;
		p=p/2;
	}
	
	for(n=m-1;n>=0;n--)
		printf("%d",a[n]);
	printf("\n");
}
void toeight()
{
	int p,m,n,a[100];
	printf("十進制轉八進制\n");
	printf("輸入十進制數:");
	scanf("%d",&p);
	for(m=0;p>0;m++)
	{
		a[m]=p%8;
		p=p/8;
	}
	
	for(n=m-1;n>=0;n--)
		printf("%d",a[n]);
	printf("\n");
}

void tosixt()
{
	int p,m,n,a;
	char ch[100];
	printf("十進制轉十六進制\n");
	printf("輸入十進制數:");
	scanf("%d",&p);
	for(m=0;p>0;m++)
	{
		a=p%16;
		if(a<10)
		{
			ch[m]=a+'0';
		}else
		{
			ch[m]=a-10+'A';
		}
		p=p/16;
	}
	
	for(n=m-1;n>=0;n--)
		printf("%c",ch[n]);
	printf("\n");
}

--11-2二進制轉十進制。也是有一個公式,好比二進制1010對應十進制是10,從前面位開始1*2^3+0*2^2+1*2^1+0*2^0=8+2=10.還有就是判斷輸入的是否是二進制數了。io

#include<stdio.h>
void towtoten();
int pow(int a);
int main()
{
    towtoten();
	return 0;
}
void towtoten()
{
	int temp,n=0,i,j,sum=0;
	char p,a[100];
	printf("\n二進制轉十進制\n");
	printf("輸入二進制數:");
	while((p=getchar())!='\n')
	{	
		a[n]=p;
		n++;
	}
	j=n;
	for(i=0;i<n;i++)
	{
		
		if(a[i]=='.')
		{
			printf("不支持小數。");
			towtoten();
			return;
		}
		if(a[i]=='-')
		{
			printf("不支持負數。");
			towtoten();
			return;
		}
		if(a[i]!='1'&&a[i]!='0')
		{
			
			printf("輸入有誤,不是二進制數。");
			towtoten();
			return;	
		}
		
		if(a[i]=='1')
		{
			temp=pow(j-1);
		}else
		{
			temp=0;
		}
		sum+=temp;
		j--;
	}
	printf("十進制數:%d",sum);
	printf("\n");
}


int pow(int a)
{
	int product=1;
	for(int i=0;i<a;i++)
	{
		product*=2;
	}
	return product;
}
相關文章
相關標籤/搜索