最大公約數:
採用輾轉相除法;
輾轉相除法百度百科
代碼:C++非遞歸實現
int gcd(int a,int b)
{
int temp = 0;
while(b)
{
temp = b;
b = a % b;
a = temp;
}
return a;
}
C++遞歸實現
gcd(int a,int b)
{
return a%b?gcd(b,a%b):b;
}
最小公倍數:
a和b的最小公倍數與最大公約數之間存在着
最大公約數 * 最小公倍數 = a*b
的關係
int lcm(int a,int b)
{
return a*b/gcd(a,b);
}
C++ cout控制浮點數精度:
double m = 1.23456789;
cout.setf(ios::fixed);
cout.set(ios::showpoint);
cout.precison(x);//x爲小數點後位數
cout << m;
sort函數降序排列
#include < alogorithm >
bool cmp(int a ,int b)
{
return a>b;
}
int num[3] = {1,2,3};
sort(num,num+3,cmp);
結構體sort:
bool cmp(node a,node b)
{
return a.x>b.y;
}
絕對值排序
int cmp(int a,int b)
{
return abs(a) < abs(b);
}
取絕對值
abs函數,函數頭文件爲:math.h/cmath
計算x的y次冪
pow函數,函數頭文件:math.h/cmath
string字符串大小寫轉換
頭文件: string, cctype,algorithm
transform(str.begin(),str.end(),str.begin(),tolower);//大寫轉小寫
transform(s.begin(), s.end(), s.begin(), toupper);//小寫轉大寫