C++ 算法
1、精确小数位数
#include<iostream>
#include<iomanip> //运用保留几位小数的函数
using namespace std;
int main(){
double res;
cout<<setprecision(3)<<fixed<<res;
return 0;
}#
# 2、ASCCI码和字符相互转化
//已知字符a求a的ascci码x
x=int('a');
//已知a的ascci码x,求a
a=char(x);
3、十进制转十六进制
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
cout<<hex<<(a+b)<<endl;
}
4、字符串切片
string n;
cin>>n;
string m=n.substr(4,2);//下标从4开始截取两个字符串
5、while(0)表示循环不运行
while(0){
//循环不运行
}
6、数组里最值
int n;
int a[100];
int jicha = *max_element(a, a + n) - *min_element(a, a + n);
7、数字转字符串
long long int n;
char x;
cin >> n>>x;
string s = "";
for (int i = 1; i <= n; i++) {
s += to_string(i);
}
8、计算string里面出现字符的个数
#include<algorithm>
int cnt = count(s.begin(), s.end(), x);
9、去重(unique)
unique只能去除相邻相同的数字
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[10] = { 0, 7, 7, 6, 1, 1, 5, 5, 8, 9 };
int n = unique(a, a + 10) - a;
cout << n << endl; // 7
for (int i = 0; i < n; i++)
cout << a[i] << " "; // 0 7 6 1 5 8 9
return 0;
}
10、push_back插入和sort排序
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> a(N);
for (int i = 0; i < N; i++) {
cin >> a[i];
}
int m;
cin >> m;
a.push_back(m);
sort(a.begin(), a.end());
for (int i = 0; i < N + 1; i++) {
cout<< a[i] << " ";
}
}
11、向上向下取整
#include<iostream>
#include<cmath>
using namespace std;
int main(){
double a;
cin>>a;
cout<<floor(a)<<endl;
cout<<ceil(a)<<endl;
}