代码改变世界

c显示数字的LED(数字转LED)

2013-08-26 01:03  youxin  阅读(1077)  评论(0编辑  收藏  举报

实现这么一个函数:传入一个int,在屏幕输出类似LED显示屏效果的字母拼图,例如:

 输入1234567890,输出:

 请注意每个字符的固定宽度和高度,两个数字间保留一个空格

 函数名:void LEDprint(int num);

此题是表驱动方法的典型应用。

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
//每个字符宽度为5,长度为7
string LEDarray[][7]={
    {" --- ", //0
     "|   |",
     "|   |",
     "|   |",
     "|   |",
     "|   |",
     " --- "},

    {"     ", //1
     "    |",
     "    |",
     "     ",
     "    |",
     "    |",
     "     "},

    {" --- ", // 2
    "    |",
    "    |",
    " --- ",
    "|    ",
    "|    ",
    " --- "},

   {" --- ",
    "    |",
    "    |",
    " --- ",
    "    |",
    "    |",
    " --- "},

   {"     ",
    "|   |",
    "|   |",
    " --- ",
    "    |",
    "    |",
    "     "},

   {" --- ",
    "|    ",
    "|    ",
    " --- ",
    "    |",  
    "    |",
    " --- "},

   {" --- ",
    "|    ",
    "|    ",
    " --- ",
    "|   |",
    "|   |",
    " --- "},

   {" --- ",
    "    |",
    "    |",
    "     ",
    "    |",
    "    |",
    "     "},

   {" --- ",
    "|   |",
    "|   |",
    " --- ",
    "|   |",
    "|   |",
    " --- "},

   {" --- ",
    "|   |",
    "|   |",
    " --- ",
    "    |",
    "    |",
    " --- "}
};
 
void LEDPrint(int num)
{
     if(num<0)
         return;
     char str[11]={'\0'};
     itoa(num,str,10);

     int len=strlen(str);
     string (*LED)[7]=new string[len][7];

     for(int i=0;i<len;i++)
     {
         int index=str[i]-'0';//重点在这里
         for(int j=0;j<7;j++)
         {
             LED[i][j]=LEDarray[index][j];
         }
     }
     
     for(int j=0;j<7;j++)
     {
         for(int i=0;i<len;i++)
         {
             cout<<LED[i][j]<<" ";
         }
         cout<<endl;
     }
     /*
      这里不能delete,因为后面的7,不能new出来的,
     for(int i=0;i<len;i++)
      delete[] LED[i];
        
    */
     delete[] LED;
}

        

int main()
{
    cout<<"input a number"<<endl;
    int num;
    while(cin>>num)
    {
        LEDPrint(num);
    }
    cout<<endl<<endl;
}

唯一值得注意的地方是delete:

  只需delete[] LED即可。后面的7不是new出来的,如果delete程序会运行错误
还有一点

还有一点,char的大小为什么是:
char str[11]
因为int类型的最大的只有10位,我们开辟11就够了。
参考:http://blog.chinaunix.net/uid-27034868-id-3811600.html