Question
- 下記の菱形★タワーを印字する(△はスペース)
- Conditions: 奇数の整数を輸入
- Example:
input_5
△△★△△
△★★★△
★★★★★
△★★★△
△△★△△
input_3
△★△
★★★
△★△
input_9
△△△△★△△△△
△△△★★★△△△
△△★★★★★△△
△★★★★★★★△
★★★★★★★★★
△★★★★★★★△
△△★★★★★△△
△△△★★★△△△
△△△△★△△△△
Solution
solution.cpp
#include <iostream>
#define SKIP 2
using namespace std;
void printStar( int stars ){
for( int i = 0; i < stars; i++ )
cout << "*";
}
void printSpace( int spaces ){
for( int i = 0; i < spaces; i++ )
cout << " ";
}
int main(void){
int times;
cout << "Input an ODD number to print star tower:\n";
cin >> times;
if( 0 == times % 2 ){
cout << "Please input an ODD number!" << endl;
return 0;
}
int stars, spaces, revPos;
// reverse point is the most stars of lines
revPos = times / 2;
for( int i = 0; i < times; i++ ){
// count stars and spaces in this line
if( i < revPos ){
stars = 1 + i * SKIP;
spaces = times - stars;
}else{
stars = times - ( i - revPos ) * SKIP;
spaces = times - stars;
}
// stars always start from the center, insert spaces in the front and tail of stars
printSpace(spaces/2);
printStar(stars);
printSpace(spaces/2); // this line can be commented out
// change line
cout << endl;
}
}