一、小东西们
1.取整cmath
去尾法取整(向下取整)
int t, a, b;
t = (a+b) / 3.0;
b[i] = static_cast<int>(floor(t));
floor 函数返回的是 double 类型,再使用 static_cast 来将 floor 函数的结果转换为整数类型。如果你确定 t 的值总是整数,你也可以直接将 t 赋值给 b[i],因为整数除法会自动向下取整。但是使用 floor 函数可以确保即使 t 不是整数,也能正确地向下取整。
向上取整
double num = 3.14;
cout << ceil(num) //4
num = -3.14;
cout << ceil(num) //-3
return 0;
}
四舍五入
round(3.14) = 3
2.保留n位小数
#include<iomanip>
cout<<fixed<<setprecision(5)<<a;//输出 0.12300
2.sort()
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int num[10] = {6,5,9,1,2,8,7,3,4,0};
sort(num,num+10,greater<int>());//降序
for(int i=0;i<10;i++){
cout<<num[i]<<" ";
}//输出结果:9 8 7 6 5 4 3 2 1 0
return 0;
}
#include <iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a<b;//升序;a>b是降序
}
int main()
{
int a[6]={3,5,8,6,2,9};
sort(a,a+6,cmp);
for(int i=0;i<6;i++)
cout<<a[i]<<" ";
return 0;
}
个位数降序
#include <iostream>
#include<algorithm>
using namespace std;
bool cmp(int x, int y)
{
return x % 10 > y % 10;
}
int main()
{
int a[5] = { 23,19,54,16,17 };
sort(a, a + 5, cmp);
for (int i = 0; i < 5; i++)
cout << a[i] << ' ';
return 0;
}