比较零碎,整理一下小点
scanf问题
- 这个是我在做一道题是碰到的,要同时输入一个字符和一个数字
- 如果用scanf的话,会多输进空格,因此用cin比较方便。
常用math函数
fabs(double x)
- 取绝对值
floor(double x)
和ceil(double x)
- 向下取整和向上取整
#include <stdio.h>
#include <math.h>
int main()
{
double db1 = -5.2, db2 = 5.2;
printf("%.0f %.0f\n", floor(db1), ceil(db1));
printf("%.0f %.0f\n", floor(db2), ceil(db2));
return 0;
}
- 输出结果
-6 -5
5 6
pow(double r, double p)
- 得到 rp
sqrt(double x)
- 算术平方根
log(double x)
- 以自然对数为底的对数
round(double x)
- 四舍五入
memset
memset(数组名, 值, sizeof(数组名))
- 按字节赋值(建议赋0或-1)
- 在
string.h
头文件内
string.h头文件
strlen(字符数组)
- 字符数组中第一个
\0
前的字符的个数
- 字符数组中第一个
strcmp(字符数组1, 字符数组2)
- 数组1 < 数组2,返回负整数
- 数组1 == 数组2,返回0
- 数组1 》 数组2,返回正整数
strcpy(字符数组1, 字符数组2)
- 把数组2赋值给数组1(包括了结束符
\0
)
- 把数组2赋值给数组1(包括了结束符
strcat(字符数组1, 字符数组2)
- 把数组2接到数组1后面
sscanf和sprintf
- 参考:笔记链接
- sscanf
- 根据格式从字符串中提取数据。如从字符串中取出整数、浮点数和字符串等
- 取指定长度的字符串
- 取到指定字符为止的字符串
- 取仅包含指定字符集的字符串
- 取到指定字符集为止的字符串
- 支持格式字符%[]
#include <stdio.h>
int main(){
int n;
double db;
char str[100] = "2048:3.14,hello", str2[100];
sscanf(str, "%d:%lf,%s", &n, &db, str2);
printf("n = %d, db = %.2f, str2 = %s\n", n, db, str2);
return 0;
}
//输出结果:n = 2048, db = 3.14, str2 = hello
- sprintf
- 将数字变量转换为字符串
- 得到整型变量的16进制和8进制字符串
- 连接多个字符串
#include <stdio.h>
int main(){
int n = 233;
char str[100];
sprintf(str, "%d", n);
printf("%s\n", str);
return 0;
}
//输出结果:233
读取一行
geiline(cin, str)
字符串输出流
istringstream stream(str);
string s;
while(stream>>s)
- 将字符流依次拿出,且不会将空格作为流,可实现字符串的空格切割
%±d
- 如果该数是整数则输出 + 反之输出 -
printf("%d%+-di", x, y);