一,字母三角形
#include<string>
#include<iostream>
using namespace std;
int main()
{
int n = 0;
cin >> n;
for (int i = 1; i <= n; i++)//i代表行数
{
string space=string(n - i, ' ');//前半部分空格
string ch = string(2 * i - 1, 'A' + i - 1);
cout << space + ch << endl;
}
return 0;//cpp文件一定要return 0
}
2,升级三角形
#include<string>
#include<iostream>
using namespace std;
int main()
{
char c;
cin >> c;
if (c >= 'A' && c <= 'Z')
{
for (int i = 1; i <= c - 'A' + 1; i++)
{
for (int j = 1; j <= c - 'A' + 1 - i; j++)
{
cout << " ";
}
for (int j = 1; j <= i; j++)
cout << (char)('A' + j-1);//输出字符要在前方括起来
for(int j=i-1;j>0;j--)
cout << (char)('A' + j-1);
cout << endl;
}
}
else if (c >= '0' && c <= '9')
{
for (int i = 1; i <= c - '1' + 1; i++)
{
for (int j = 1; j <= c - '1' + 1 - i; j++)
{
cout << " ";
}
for (int j = 1; j <= i; j++)
cout << (char)('1' + j - 1);//输出字符要在前方括起来
for (int j = i - 1; j > 0; j--)
cout << (char)('1' + j - 1);
cout << endl;
}
}
return 0;//cpp文件一定要return 0
}
3,寻找字符串
#include<cstdio>
#include<cstring>
char s1[1005], s2[1005];
int main()
{
fgets(s1, 1004, stdin);
fgets(s2, 1004, stdin);
int ans = 0;
int l1 = strlen(s1)-1; int l2 = strlen(s2)-1;
for ( int i = 0; l2 + i-1 < l1; i++)
{
bool mach = true;
for (int j = 0; j< l2; j++)
{
if (s1[i + j] != s2[j])
{
mach = false;
break;//结束循环从下一个字符开始寻找
}
}
if (mach) {
ans++;
}
}
printf("%d", ans);
return 0;
}
4,日期计算
#include<iostream>
#include<string>
using namespace std;
int whatday(int y, int m, int d)
{//分析 2019 11 29日 前面有完整的2018个年份,1-11月加28天
//返回正确的星期,用0-6表示1-7
int nas= 0;
for (int i = 1; i < y; i++)//当年还没有过完,要减1
{
if ((i % 4 == 0 && i % 100 != 0 )|| i % 400 == 0)//闰年判断条件
{
nas += 366%7;
nas%=7;
}
else {
nas += 365 % 7;
nas %= 7;
}
}
for (int i = 1; i < m; i++)
{
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
{
nas += 31 % 7;
nas %= 7;
}
else if (i == 4 || i == 6 || i == 9 || i == 11 )//一定要用else if构成并列关系,否则if下面又有else if,只有下半部分发生并列
{
nas += 30 % 7;
nas %= 7;
}
else if ((y % 4 == 0 && y % 100 != 0 )|| y % 400 == 0)
{
nas += 29%7;
nas %= 7;
}
else
{
nas += 28 % 7;
nas = nas % 7;
}
}
nas += d - 1;//关于为什么是-1,不减1则余数顺序为1234567 对应1,2,3,4,5,6,0,减一后变为0,1,2,3,4,5,6,符合下标
//天数不需要循环了
return nas%7;
}
string weekday[7] = { "Monday","Tusday","Wednesday","Thursday","Friday","Saturday","Sunday"};
int main()
{
int y, m, d;
cin >> y >> m >> d;
cout << weekday[whatday(y, m, d)] << endl;
return 0;
}
或者:
int whatday(int y,int m,int d){
if(m<=2){
m+=12;
y--;}
return (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;}