# 函式練習的題解 --- # 費氏數列公因數 - 想法 : 利用建表的方式得到費氏數列每一項,再利用__gcd函式(上禮拜有講)來取得最大公因數 - 題解 : ``` cpp= #include<bits/stdc++.h> #define ll long long using namespace std; int main(){ ll a,b,F[10000]; F[0]=0,F[1]=1; for(int i=2;i<91;++i){ F[i]=F[i-1]+F[i-2]; } int n; cin >>n; for(int i=0;i<n;++i){ cin >>a>>b; cout<<__gcd(F[a],F[b])<<'\n'; } return 0; } ``` ---- # 計算練習 - 想法 : 建立四個副函式即可 ``` cpp= #include<bits/stdc++.h> #define ll long long #define MXN 100005 using namespace std; void add(ll a,ll b){ cout<<a+b<<'\n'; } void min(ll a,ll b){ cout<<a-b<<'\n'; } void mul(ll a,ll b){ cout<<a*b<<'\n'; } void divi(ll a,ll b){ cout<<a/b<<'\n'; } int main(){ ll n,a,b;char op; cin >>n; for(int i=0;i<n;++i){ cin >>a>>op>>b; if(op=='+')add(a,b); if(op=='-')min(a,b); if(op=='*')mul(a,b); if(op=='/')divi(a,b); } } ``` ---- # 字串處理 - 想法1:直接使用STL string的函式 - 題解: ```cpp= #include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0);cin.tie(0); int op; while(cin>>op){ if(op==1){ string a; cin>>a; cout<<a.size(); }else if(op==2){ string a; cin>>a; reverse(a.begin(),a.end()); cout<<a; }else{ string a,b; cin>>a>>b; cout<<(a==b?"Yes":"No"); } cout<<"\n"; } } ``` - 想法2:字元陣列,手刻函式 - 題解: ``` cpp= #include<bits/stdc++.h> using namespace std; int length(char s[]); void reverse(); void cmp(); char s1[505],s2[505]; int main(){ char s[505]; int mod; while(cin >>mod){ cin.ignore(); cin.getline(s1,500); if(mod==1)cout<<length(s1)<<'\n'; if(mod==2)reverse(); if(mod==3)cmp(); } } int length(char s[]){ int i=1; while(s[i]!='\0')++i; return i; } void reverse(){ int l=length(s1); for(int i=l-1;i>=0;--i)cout<<s1[i]; cout<<'\n'; } void cmp(){ cin.getline(s2,500); int l1=length(s1),l2=length(s2); if(l1!=l2){ cout<<"No\n"; return; } for(int i=0;i<l1;++i){ if(s1[i]!=s2[i]){ cout<<"No\n"; return; } } cout<<"Yes\n"; return; } ``` ###### tags: `題解` > *2022/1/2 * > [name=WXDai] [time=Sun, Jan 02, 2022 00:40 ] [color=#907bf7]