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 }
  • 相关阅读:
    4.3 DDL 数据类型
    Log4j的简要概述
    Eclipse/IDEA使用小技巧
    idea-生成key的Java代码
    Java8新特性--lamada详解
    JQuery基本语法
    EL与Velocity基本语法总结:
    RAF(RandomAccessFile)类
    Java篇-File类之常用操作
    Java篇-File类之创建删除
  • 原文地址:https://www.cnblogs.com/LYLtim/p/2127790.html
Copyright © 2011-2022 走看看