1.将一个数字字符转换成数字:
char ch='3';//'3'的ascii值是51
int a;
a=ch-'0'; //'0'的ascii值是48
printf("%d",a);
输出结果:3
2.将单个整型数字转换成字符:
int a=6;
char ch;
ch=a+'0';//或者ch=a+48; '0'的ascii值是48
printf("%c",ch);
输出结果为:6
3.将字符串转换成数字(整数或者浮点数):
方法一:利用sscanf();
#include <stdio.h>
int main()
{
char str[]="10086";
int s;
sscanf(str,"%d",&s);//将str字符数组里的内容转化成整型放在s里,在c++需要包含头文件#include <stdio.h>
printf("%d",s);
return 0;
}
输出结果:10086
方法二:利用库函数atoi()或atof()、atol()、atoll()
#include <stdio.h>
#include<stdlib.h>
int main()
{
char str[]="10086.666";
int s;
double k;
printf("%d ",s=atoi(str));
printf("%f",k=atof(str));
return 0;
}
输出结果:10086 10086.666000
4.将数字转换成字符串:
方法一:利用sprintf()
#include <stdio.h>
int main()
{
char str[10];
int s=10086;
sprintf(str,"%d",s);
printf("%s",str);
return 0;
}
方法二:利用itoa(),itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用 的基数。在上例中,转换基数为10。10:十进制;2:二进制...
#include <stdio.h>
#include<stdlib.h>
int main()
{
char str[10];
int s=10086;
itoa(s,str,10);//itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用 的基数。在上例中,转换基数为10。10:十进制;2:二进制...
printf("%s",str);
return 0;
}
输出结果:10086