C/C++打印菱形

编写函数diamond打印一个菱形。如果调用diamond(3, '*')则打印:

	*
*	*	*
	*

如果调用diamond(5, '+')则打印:

		+
	+	+	+
+	+	+	+	+
	+	+	+
		+

如果用偶数做参数则打印错误提示。

 

/*每一行的星号和空格的数量是纵坐标i的函数关系,
**图形关于横轴对称,
**因此字符的数量就和字符的纵坐标距离中间位置的距离有关,
**这个距离就是纵坐标减去中间位置纵坐标的绝对值。
**By LYLtim
*/

#include<stdio.h>
#include<math.h>

void diamond(unsigned n, char c)
{
    unsigned i;
    for (i = 1; i <= n; i++) {
	    unsigned d = abs(i - n / 2 - 1), j;
	    for (j = 1; j <= d; j++) printf(" ");
	    for (j = 1; j <= (n / 2 + 1 - d) * 2 - 1; j++) printf("%c", c);
	    printf("\n");
    }
}

int main(void)
{
    unsigned n;
    char c;
    printf("Input n, c:");
    scanf("%u %c", &n, &c);
    if (n & 1 == 0) printf("error\n");
    else diamond(n, c);
    return 0;
}

 

更简洁方法(C++代码):

 1 // By LYLtim
 2 
 3 #include <iostream>
 4 #include <cmath>
 5 
 6 using namespace std; 
 7 
 8 inline int dabs(int n) { return n >= 0 ? n : - n; }
 9 void diamond(int n, char c) {
10     n >>= 1;
11     for (int i = -n; i <= n; i++) { 
12         for (int j = -n; j <= n; j++)
13             if (dabs(i) + dabs(j) <= n)
14                 cout << c;
15             else
16                 cout << ' ';
17         cout << endl;
18     }
19 }
20 
21 int main() {
22     diamond(5, '+');
23 }

 

转载于:https://www.cnblogs.com/LYLtim/archive/2011/08/04/2127790.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值