1. 输出字母三角形
#include <iostream> using namespace std; #include <string> int main() { int n; cin>>n; for(int i=1;i<=n;i++){ string space = string(n-i,' '); string ch = string(2*i-1,'A'+i-1); cout<<space+ch<<endl; } return 0; }
找到规律用两个字符串拼接起来
——————————————————————————————————————
2.输入字母或者数字,打印出图形
#include <iostream> using namespace std; #include <string> int main() { char ch; cin>>ch; if(ch>='A'&&ch<='Z'){ for(int i=1;i<= ch-'A'+1;i++){ for(int j=1;j<=ch-'A'+1-i;j++) cout<<" "; //打印空格 for(int j=1;j<=i;j++) cout<<char('A'+j-1); //打印出现字母或者数字到最中间 for(int j=i-1;j>=1;j--) cout<<char('A'+j-1); //从后往前打印 cout<<endl; } } else { for(int i=1;i<= ch-'1'+1;i++){ for(int j=1;j<=ch-'1'+1-i;j++) cout<<" "; for(int j=1;j<=i;j++) cout<<char('1'+j-1); for(int j=i-1;j>=1;j--) cout<<char('1'+j-1); cout<<endl; } } return 0; }
总结:分成三个部分进行打印,找出规律出来,根据行数和列数,找出求解
——————————————————————————————————————
3.造房子,找规律
#include <iostream> using namespace std; #include <string> int main() { int n,m; cin>>n>>m; //实际要输出2*n+1行 for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++) cout<<"+-"; //根据行中的房子数 开始建造 对应i组的第一行 cout<<"+"<<endl; for(int j=1;j<=m;j++) cout<<"|*"; //对应i组的第二行 cout<<"|"<<endl; //每次要补上 } for(int j=1;j<=m;j++) //这是最后一行多出来的 cout<<"+-"; cout<<"+"; return 0; }
总结:根据房子数确定行列与其中对应的规律进行搭建,重要还是找规律
——————————————————————————————————————
5. 找相同字符串个数
#include <iostream> using namespace std; #include <cstring> #include <cstdio> char s1[1005],s2[1005]; int main() { fgets(s1,1004,stdin); //会把换行符也会读入进去 fgets(s2,1004,stdin); int len1,len2,ans=0; len1 = strlen(s1)-1,len2 = strlen(s2)-1; //streln得到里面个数要减去一个换行符 for(int i=0;i+len2-1<=len1;i++) //i+len2-1<len1作为结束条件 { bool match = true; for(int j=0;j<len2;j++) //进行比较 if(s1[i+j]!=s2[j]){ match = false; break; } if(match) ans++; } printf("%d",ans); return 0; }
总结:使用fgets进行读取一行,再进行比对
——————————————————————————————————————
6.给出年月日求出当天是周几