zoukankan      html  css  js  c++  java
  • C语言-数字字符串转换成这个字符串对应的数字(十进制、十六进制)

    数字字符串转换成这个字符串对应的数字(十进制、十六进制)

    (1)数字字符串转换成这个字符串对应的数字(十进制)

    要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。

    提示:你每发现一个数字,把当前值乘以10,并把这个值和新的数字所代表的值相加。

    思路:字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。 

    代码如下:

    #include <stdio.h>
    #include <assert.h>
    int my_atoi(char *str)
    {
        int n = 0;
        int flag = 0;
        assert(str);
        if(*str == '-')
        {
            flag = 1;
            str++;
        }
        while(*str >= '0' && *str <= '9')
        {
            n = n*10 + (*str - '0');
            str++;
        }
        if(flag == 1)
        {
            n = -n;
        }
        return n;
    }
    int main ()
    {
        char a[] = "12";
        char b[] = "-123";
        printf("%d
    %d
    ",my_atoi(a),my_atoi(b));
        return 0;
    }

    (2)数字字符串转换成这个字符串对应的数字(十六进制)

    要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。

    提示:你每发现一个数字,把当前值乘以16,并把这个值和新的数字所代表的值相加。

    思路:字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。 

    代码如下:

    #include <stdio.h>
    #include <assert.h>
    #include <iostream>
    
    using namespace std;
    
    int change(char* str)
    {
        assert(str);
        int result = 0;
        int flag = 0;
    
        if (*str == '-') 
        {
            flag = 1;
            str++;
        }
    
        while (*str) 
        {
            if (*str >= '0' && *str <= '9')
                result = result * 16 + (*str - '0');
            else if (*str >= 'a' && *str <= 'f')
                result = result * 16 + (*str - 'a' + 10);
            else if (*str >= 'A' && *str <= 'F')
                result = result * 16 + (*str - 'A' + 10);
            else {
                cout << "非法字符!" << endl;
                return 0;
            }
            str++;
        }
    
        if (flag == 1) result = -result;
    
        return result;
    }
    
    int main()
    {
        char str[] = "-16";
        int res = change(str);
        cout << res << endl;
    
        return 0;
    }
  • 相关阅读:
    Oracle ORA07445 [evaopn3()+384] 错误 分析
    Openfiler iscsiadm: No portals found 解决方法
    Openfiler iscsiadm: No portals found 解决方法
    ORA00600 [kmgs_parameter_update_timeout_1], [27072] ORA27072 解决方法
    Oracle 安装 Error in writing to directory /tmp/OraInstall 错误 说明
    Oracle alert log ALTER SYSTEM SET service_names='','SYS$SYS.KUPC$C_...' SCOPE=MEMORY SID='' 说明
    Oracle latch:library cache 导致 数据库挂起 故障
    ORA600 [4194] 说明
    ORA00600:[32695], [hash aggregation can't be done] 解决方法
    Oracle 10g Rac root.sh Failure at final check of Oracle CRS stack 10 解决方法
  • 原文地址:https://www.cnblogs.com/zkfopen/p/11060685.html
Copyright © 2011-2022 走看看