Linux C 知识 char型数字转换为int型 int型 转换为Char

前言

在九度oj做acm的时候,经常会遇到了char类型和int类型相互转化的问题,这里进行一下总结。今后,可能会多次更新博客,因为半年做了很多总结,但是都是保存在word文档上了,现在开始慢慢向CSDN博客转移。

问题类型

char型数字转换为int型

转换方法

 
a[i] - '0'  

参考程序 

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
int main()  
{  
    char str[10];  
    int i, len;  
  
    while(scanf("%s", str) != EOF)  
    {  
        for(i = 0, len = strlen(str); i < len; i++)  
        {  
            printf("%d", str[i] - '0');  
        }  
        printf("
");  
    }  
  
    return 0;  
}  

int类型转化为char类型

转换方法 

a[i] + '0'  

参考程序

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
int main()  
{  
    int number, i;  
    char str[10];  
  
    while(scanf("%d", &number) != EOF)  
    {  
        memset(str, 0, sizeof(str));  
      
        i = 0;  
        while(number)  
        {  
            str[i ++] = number % 10 + '0';  
            number /= 10;  
        }         
        puts(str);        
    }  
  
    return 0;  
}  
原文地址:https://www.cnblogs.com/aspirant/p/3545324.html