c语言 11-10

1、字符串转换为int型

#include <stdio.h>

int toint(char *s1)
{
    int i, j = 0;
    while(*s1)
    {
        for(i = 0; i <= 9; i++)
        {
            if((*s1 - '0') == i)
                j = j * 10 + i;
        }
        s1++;
    }
    return j;
}

int main(void)
{
    char str1[128];
    printf("str1: "); scanf("%s", str1);
    
    printf("result converted to int type: %d\n", toint(str1));
    return 0;
}

 

 

2、转换为long型

#include <stdio.h>

long tolong(char *s1)
{
    int i;
    long j = 0;
    while(*s1)
    {
        for(i = 0; i <= 9; i++)
        {
            if((*s1 - '0') == i)
                j = j * 10 + (long)i;
        }
        s1++;
    }
    return j;
}

int main(void)
{
    char str1[128];
    printf("str1: "); scanf("%s", str1);
    
    printf("result converted to long type: %ld\n", tolong(str1));
    return 0;
}

 

 

3、转换为double型

#include <stdio.h>

double todouble(char *s1)
{
    int i;
    double j = 0.0;
    while(*s1)
    {
        for(i = 0; i <= 9; i++)
        {
            if((*s1 - '0') == i)
                j = j * 10 + (double)i;
        }
        s1++;
    }
    return j;
}

int main(void)
{
    char str1[128];
    printf("str1: "); scanf("%s", str1);
    
    printf("result converted to double type: %f\n", todouble(str1));
    return 0;
}

 

posted @ 2021-06-03 12:24  小鲨鱼2018  阅读(57)  评论(0编辑  收藏  举报