天天看點

實驗7-3-6 字元串轉換成十進制整數實驗7-3-6 字元串轉換成十進制整數(C語言)

實驗7-3-6 字元串轉換成十進制整數(C語言)

題目描述

輸入一個以#結束的字元串,本題要求濾去所有的非十六進制字元(不分大小寫),組成一個新的表示十六進制數字的字元串,然後将其轉換為十進制數後輸出。如果在第一個十六進制字元之前存在字元“-”,則代表該數是負數。

輸入

輸入在一行中給出一個以#結束的非空字元串。

輸出

在一行中輸出轉換後的十進制數。題目保證輸出在長整型範圍内。

樣例輸入

+-P-xf4+-1!#

樣例輸出

-3905

代碼

#include<stdio.h>
#include<string.h>
#include<math.h>
int main()
{
    int i,j=0,last=0,count;
    char c1[10000],a='0',b='0';
    for(i=0,j=0;;i++)
    {
        scanf("%c",&c1[i]);
        if(c1[i]=='#')
        {
            break;
        }
        else if(c1[i]=='+'||c1[i]=='-')
        {
            a=c1[i];
        }
        else if((c1[i]>='0'&&c1[i]<='9'||c1[i]>='A'&&c1[i]<='F'||c1[i]>='a'&&c1[i]<='f')&&a!='0')
        {
        	j++;
        	if(j==1)
        	{
        		b=a;
        	}
        }
    }
    for(i=0,count=0;i<strlen(c1);i++)
    {
        if(c1[i]>='0'&&c1[i]<='9'||c1[i]>='A'&&c1[i]<='F'||c1[i]>='a'&&c1[i]<='f')
        {
        	count++;
        }
    }
    for(i=0,j=count-1;i<strlen(c1),j>=0;i++)
    {
    	 if(c1[i]>='0'&&c1[i]<='9')
    	 {
    	 	last=last+(c1[i]-48)*pow(16,j);
    	 	j=j-1;
    	 }
    	 else if(c1[i]>='A'&&c1[i]<='F')
    	 {
    	 	last=last+(c1[i]-55)*pow(16,j);
    	 	j=j-1;
    	 }
    	 else if(c1[i]>='a'&&c1[i]<='f')
    	 {
    	 	last=last+(c1[i]-87)*pow(16,j);
    	 	j=j-1;
    	 } 
    }
    if(b=='+'||b=='0')
    {
        printf("%d\n",last);
    }
    else if(b=='-')
    {
    	printf("%c%d\n",b,last);
    }
    return 0;
}
           

繼續閱讀