当前位置:网站首页>Exercise 7-8 converting strings to decimal integers (15 points)

Exercise 7-8 converting strings to decimal integers (15 points)

2022-07-04 09:47:00 skeet follower

Enter a to # Ending string , This problem requires that all non hexadecimal characters be filtered out ( Case insensitive ), Form a new string of hexadecimal digits , Then convert it to decimal number and output . If there is a character before the first hexadecimal character “-”, It means that the number is negative .

Input format :

The input gives one in a line to # The ending non empty string .

Output format :

Output the converted decimal number on one line . Ensure that the output is in the long integer range .

sample input :

+-P-xf4+-1!#

sample output :

-3905

The code is as follows :

#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
    char str[80]= {'\0'};
    int i=0,k=0,m,sum=0;
    char c;
    scanf("%c",&c);
    int flag = 1,flag1=1;
    while(c!='#')
    {
        if(c>='a'&&c<='f')
        {
            flag=0;
            str[i]=c-87;
            i++;
        }
        else if(c>='A'&&c<='F')
        {
            flag=0;
            str[i]=c-55;
            i++;
        }
        else if(c>='0'&&c<='9')
        {
            flag =0;
            str[i]=c-48;
            i++;
        }
        else if(c=='-'&&flag==1){// Determine whether there is a character before the first hexadecimal character “-”
            flag1=-1;
        }
 
        scanf("%c",&c);
 
    }
 
    for(m=i-1;m>=0;m--){// Hexadecimal to decimal ;
      sum+=str[m]*pow(16,k);
        k++;
    }
 
    printf("%d",flag1*sum);
 
    return 0;
}

原网站

版权声明
本文为[skeet follower]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141423487472.html