1.按照題目描述,輸出字母三角形
樣例輸入1
2
樣例輸出1
A
BBB
樣例輸入2
3
樣例輸出2
A
BBB
CCCCC
代碼實現:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i,n;
cin >> n;
for (i = 1;i<=n;i++)
{
string space = string(n-i,' ');
string zimu = string(2*i-1,'A'+i-1);
cout<<space + zimu <<endl;
}
return 0;
}
總結:
利用了C++string類中的拼接方法,將空格數量和字母數量分別找規律進行計算,然後將結果拼接。
2.這次輸出一個稍微複雜的三角形,輸入一個大寫字母或一個數字會產生不一樣的效果。
樣例輸入1
F
樣例輸出
樣例輸入2
3
樣例輸出
#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(j = 1;j <= i;j++){
cout << (char)('A' + j - 1);
}
for(j = i - 1; j >= 1;j--){
cout << (char)('A' + j - 1);
}
cout << endl;
}
}
else{
for (int i = 1;i <= c - '1' + 1;i++){
for(int j = 1; j <= c-'1'+1-i;j++){
cout << " ";
}
for(j = 1;j <= i;j++){
cout << (char)('1' + j - 1);
}
for(j = i - 1; j >= 1;j--){
cout << (char)('1' + j - 1);
}
cout << endl;
}
}
return 0;
}
總結:找規律先將空格輸出,然後再按照規律輸出字母。