题意:
根据输入画出三角波型, 第一行读入的是 case 数; 每个 case 包含两行, 第一行是三角形的振幅/高度, 第二行是三角形重复的次数.
不同输入 case 之间使用空行进行分隔. 输出的波形也需使用空行进行分隔.
思路:
读入 amplitude 和 frequency 后, 逐个三角形进行输出, 输出 frequency 次. 注意三角形包含上三角和下三角.
要点:
1. 使用 getline() 逐行读入.
2. 使用 atoi 转 string 为 int.
3. 最后一个 case 的最后一个波型, 不能再输出空行进行分隔, 否则会报 wrong answer.
代码:
# include <iostream>
# include <string>
# include <cstdio>
# include <cstdlib>
using namespace std;
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen ("488_i.txt", "r", stdin);
freopen ("488_o.txt", "w", stdout);
#endif
string caseNum;
getline(cin, caseNum);
int n = atoi(caseNum.c_str());
string blank;
getline(cin, blank); // 读取空行
string amplitude; // 振幅/高度
string frequency; // 重复次数
for(int m=0; m<n; m++){
getline(cin, amplitude);
getline(cin, frequency) ;
getline(cin, blank); // 读取空行
int a = atoi(amplitude.c_str());
int f = atoi(frequency.c_str());
for(int i=0; i<f; i++){
// 上三角
for(int j=1; j<=a; j++){
for(int k=1; k<=j; k++){
cout << j;
}
cout << endl;
}
// 下三角
for(int j=a-1; j>0; j--){
for(int k=j; k>0; k--){
cout << j;
}
cout << endl;
}
// 保证最后不会输出一个空行
if(i != f-1 || m != n-1){
cout << endl;
}
}
}
return 0;
}
环境:C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE