一、提取一个整数的每位数
形状如下
//num是输入,arr、len是输出,结果在arr中按从低位到高位排放。
num=n;
len=0;
while(num){
arr[len++]=num%10;
num/=10;
}
二、辗转相除求最大公约数
int gcd(int a,int b){
int t;
if(a<b){///使a大b小
t=b;b=a;a=t;
}
while((t=a%b)!=0){///余数不为0时
a=b;///被除数作除数
b=t;///余数作被除数
}///余数总是比除数小
return b;///最后整除的除数是最大公约数
}
三、关于int,long,long long有多长
int最大为2147483647,大于10位,long和int一样大;uint大一倍,也是大于10位。long long最大为9223372036854775807,不到20位;unsigned long long大一倍,大于20位,比20的阶乘大。scanf("%I64d",&ago);
四、set、map用法
///set是集合的意思,集合内元素无重复。
set<int> arr;//定义
arr.insert(100);///把元素添进集合
arr.size();///元素个数
set<int>::iterator it;//遍历
for(it=arr.begin();it!=arr.end();it++){
cout<<(*it)<<endl;
}
需要注意的是。如果set内放的是double或者float,存在精度问题,需要自己手动解决,比如不用double,舍去部分用unsigned long long或者手动判断。
/***
map是映射的意思,是<key,value>的二元组,key无重复,
主要功能是根据key查找value
***/
map<string,int> arr;
arr[ss]=100;///插入
arr.size();///元素个数
map<string,int>::iterator it;///遍历
for(it=arr.begin();it!=arr.end();){
cout<<it->frist<<it->second<<endl;
if(arr->second==0){
arr.erase(it);
}else{
it++;
}
}
map常用于单词计数。字符计数。
五、string或char*类型转为其他类型
#include<stdlib.h>
转浮点 float a=atof(”-12345.90“);
转整数 int b=atof(str.c_str());
转长整数 long c=atof("qwer123456");//结果为123456
六、双表思想
后台维护一个表,前台显示一个表。
七、读写文件
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main(){
char fname[20]="abc.txt";
ofstream out(abc.txt);
if(out.is_open()){
out<<"Hello,file!"<<endl;
}
char buffer[1024];
ifstream in("abc.txt");
if(!in.is_open()){
cout<<"open file failed!"<<endl;
exit(1);
}
while(!in.eof()){
in.getline(buffer,256);
cout<<buffer<<endl;
}
in.close();
return 0;
}