打印沙漏 (20 分)
主要还是等差公式: 等差数列前n项和: (1) Sn = n*(a1 + an) / 2 (2)
#include <iostream> #include <cmath> using namespace std; int main() { int n, m; char sign; cin >> n >> sign; m = sqrt((n + 1) / 2 ); int k = 1; for(int i = m; i >= 1; i --) { for(int i = 1; i < k; ++ i) cout << " "; k ++; for(int j = 1; j <= 2*i - 1; ++ j) cout << sign; cout << endl; } k --; for(int i = 2; i <= m; i ++) { k --; for(int i = 1; i < k; ++ i) cout << " "; for(int j = 1; j <= 2*i - 1; ++ j) cout << sign; cout << endl; } cout << (n - 2 * m * m + 1) << endl; return 0; }
最开始尝试用递归求解, 但是递归爆栈了, 又改用循环.