设置width,不用嵌套循环打印X对角线
X形图案
http://www.nowcoder.com/questionTerminal/83d6afe3018e44539c51265165806ee4
#include <iostream> using namespace std; int main() { // width 间隔宽度 margin 边距 down判断是否打印完上部分 int length, width, down = 0, margin = 1; cin >> length; width = length - 2; for (int i = 0; i < length; i++) { if (width >= 0) { cout.width(margin); cout << '*'; cout.width(width+1); cout << '*'; // 最终减到0为偶数长度 if (width == 0) { cout << endl; cout.width(margin+1); down = 1; i++; cout << "**"; } } else { cout.width(margin); cout << '*'; down = 1; } cout << endl; if (!down) { width -= 2; ++margin; }// 还在打上半部分 else { width += 2; --margin; } } return 0; }