c语言中如何将字符串转化成整数型并输出?

Python019

c语言中如何将字符串转化成整数型并输出?,第1张

在C语言中将字符串转化成整型有两种方法。

1 用atoi函数。

atoi的功能就是将字符串转为整型并返回。其声明为

int atoi(char *str)

比如atoi("1234")会返回整型1234。

2 用sscanf。

sscanf与标准格式化输入函数scanf类似,不过源并非是标准输入,而是字符串。

用sscanf可以处理更复杂的字符串。

比如字符串char * str = "a=1, b=2"

定义int a,b后

可以用

sscanf(str,"a=%d, b=%d",&a,&b)

来将a,b值提取,计算后,a=1, b=2。

1 方法有强制转换、使用库函数round,ceil,floor等

2 使用示例

#include<stdio.h>

#include<math.h>

int main(){

float f = 12.5

int a = (int)f//强制转换 直接取整

int b = round(f)//四舍五入取整

int c = ceil(f)//向上取整

int d = floor(f)//向下取整

printf("a=%d\nb=%d\nc=%d\nd=%d\n", a, b, c, d)

getchar()

return 0

}

3 运行结果