类型转换函数的代码实现

写在之前的话:之前一直在搞学校的竞赛项目,忙了好久(咸了好久 ),现在项目验收了 稍微清静了点,就更新一下之前学习的成果(炒炒冷饭 )。

再来谈谈为什么要做这样一个整合呢,之前在学习过程中了解到:类型转换函数itoa、itof等本身代码实现并不困难,但正因为简单且平时使用的很少,所以容易被忽视,并且在近几年的企业面试中也曾作为考题出现过,所以觉得有必要总结记忆一下(将来好混口饭吃 )。
不多废话,贴代码了

1.itoa代码实现

#include <stdio.h>

int main()
{
    
    
    int int_a;
    float float_b;

    float c = 1.00;

    printf("输入需要转换的整形数据:\n");
    scanf("%d", &int_a);

    float_b = int_a / c;

    printf("转换结果为:\n%f\n", float_b);

    return 0;
}

2.itoa代码实现

#include <stdio.h>

void my_itoa(int a, char *b)
{
    
    
    int i;
    int n;
    int j;
    
    int t = 0;
    
    if (a < 0)
    {
    
    
        t = 1;
        a = -a;
    }
    for (n = 0, j = a; j > 0; j /= 10, n++)
        ;
    *(b + n) = '\0';

    for (i = n - 1; i >= 0; i--)
    {
    
    
        *(b + i + t) = a % 10 + '0';
        a = a / 10;
    }
    if (t)
    {
    
    
        *b = '-';
    }
}

int main()
{
    
    
    int a;
    char b[10] = {
    
    0};
    //int a = -899;

    printf("输入要转换的整形数据a:\n");
    scanf("%d", &a);

    my_itoa(a, b);

    printf("转化成的字符型数据b[10] = %s\n", b);

    return 0;
}

3.atoi代码实现

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

int my_atoi(const char *str)
{
    
    
    int result = 0;
    int flag = 1;

    while (*str == ' ')
    {
    
    
        str++;
    }

    if (*str == '-')
    {
    
    
        flag = 0;
        str++;
    }
    else if (*str == '+')
    {
    
    
        flag = 1;
        str++;
    }
    else if (*str >= '9' || *str <= '0')
    {
    
    
        return 0;
    }

    while (*str != '/0' && *str <= '9' && *str >= '0')
    {
    
    
        result = result * 10 + *str - '0';
        str++;
    }

    if (flag == 0)
    {
    
    
        result = -result;
    }

    return result;
}

int main(int argc, char *argv[])
{
    
    
    char *ptr = "1234";
    int n;

    n = my_atoi(ptr);
    printf("Input:%d\n", n);

    n = atoi(ptr);
    printf("Result:%d\n", n);
    return 0;
}

未来可能更新其他类型转换函数(画饼时刻
以上,欢迎交流指正。

猜你喜欢

转载自blog.csdn.net/qq_45792897/article/details/115386671
今日推荐