cstdlib、cmath库用法总结

本文深入探讨了C++标准库中的多个关键函数,包括类型转换函数如atof、atoi和atol,以及更复杂的字符串到数字转换函数如strtod、strtof等。此外,还介绍了随机数生成、数学运算和内存管理函数,如rand、srand、pow和malloc。通过实例展示了这些函数的使用方法和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

cstdlib

atof, atoi, atol, strtod, strtof, strtols, strtol, strtoll, strtoul, strtoull, rand, srand, calloc, free, malloc, realloc, abort, atexit, exit, getenv, system, bsearch, qsort, abs, div, labs, ldiv, llabs, tlldiv, mblen, mbtowc, wctomb, mbstowcs, wcstombs

  • atof、atoi、atol
cout<<atoi("546.1")<<endl;//546
cout<<atof("546.1")<<endl;//546.1
cout<<atol("546.1")<<endl;//546
  • strtod, strtof, strtols, strtol, strtoll, strtoul, strtoull

不仅可以字符串转数字,还可以顺带进制转换!

	string s;
	char *c;
	cout<<strtod("213.454mkomo",&c)<<endl;        //213.454
	cout<<c<<endl;                                //mkomo
	cout<<strtof("213.454mkomo",&c)<<endl;        //213.454
	cout<<c<<endl;                                //mkomo
	cout<<strtol("123456789.454mkomo",&c,3)<<endl;//5
	cout<<c<<endl;                                //3456789.454mkomo
	cout<<strtoll("213.454mkomo",&c,10)<<endl;    //213
	cout<<c<<endl;                                //.454mkomo
	cout<<strtoul("213.454mkomo",&c,10)<<endl;    //213
	cout<<c<<endl;                                //.454mkomo
  • rand、srand
srand((unsigned)time(0));
cout<<rand()<<endl;
  • abs、labs
cout<<abs(-45.67)<<endl;//45.67
cout<<labs(-45.67)<<endl;-45.67

cmath

  • pow
cout<<pow(2,3)<<endl;//8
  • sqrt
  • fabs
cout<<fabs(-45.67)<<endl;//45.67

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值