用星号打印菱形
题目:用*打印菱形,*中间以空格隔开
如n=5时输出如下图形:
*
* * *
* * * * *
* * *
*
要求根据输入的n打印出相应的菱形
代码:
#include<iostream> using namespace std; int main() { int n; cin >> n; if (n % 2 == 0) cout << "请输入奇数!"; else { int x = n / 2 + 1; int a = 1; for (int i = 1;i <= n;i++) { if (i <=x) { int b = x - i; for (int j = 1;j <= b;j++) { cout << " "; } for (int k = 1;k <= a;k++) { cout << "*" << " "; } cout << endl; if(i<x)a = a + 2; } else { a = a - 2; int b = i-x; for (int j = 1;j <= b;j++) { cout << " "; } for (int k = 1;k <= a;k++) { cout << "*" << " "; } cout << endl; } } } return 0; }