Question
-
下記の砂時計形★タワーを印字する(△はスペース)
-
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 hourglass:\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 = times - i * SKIP;
spaces = times - stars;
}else{
stars = times - ( ( times - ( i + 1 ) ) * 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;
}
}