zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    「十二省联考2019」 春节十二响
    「八省联考2018」 劈配
    斯特林数
    「POJ2505」A multiplication game [博弈论]
    [luogu2048] [bzoj2006] [NOI2010] 超级钢琴 题解
    [HNOI2002]-洛谷2234-营业额统计-Treap
    平衡树Treap模板与原理
    KMP算法讲解
    高斯消元--模板,原理
    第一篇博客!!
  • 原文地址:https://www.cnblogs.com/LYLtim/p/2127790.html
Copyright © 2011-2022 走看看