C++数据转换

char* to int

  • const char* a = "123"; int b = atoi(a);
  • 手写atoi:
int atoi(const char* str) {
	const char* p = str;
	bool neg = false;
	int res = 0;
	if (*str == '-' || *str == '+') {
		str++;
	}

	while (*str != 0) {
	//可以在此处加判断是否当前char为数字
		res = res * 10 + *str - 48;
		str++;
	}

	if (*p == '-') {
		res = -res;
	}
	return res;
}

int to char*

int a = 123;
// b此处不能使用char*,因为那是const的
char b[4];
_itoa_s(a, b, 10);

float to int

float f = 9.87;
// 默认向下取整
int a = (int)f;

// round(), floor(), ceil()
// round(f) = 10; 四舍五入
// floor(f) = 9; 向下取“地板”
// ceil(f) = 10; 向上取“天花板“
// 三个函数结果可以为int,也可以为float,double,long

int to float

int a = 10;
float f = (float)a;
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值