您好,想搞清楚静态变量,全局变量的问题,下面是这个程序不报错,但是也不能执行我想要的
时间:10-02
整理:3721RD
点击:
程序实现,数码管显示2016开始,一秒加一,到2026时候,一秒加二;这里变量count,出来问题,我用了全局变量的形式,同时又在num()函数中用了局部变量的形式。按道理系统应该默认为局部变量。那为什么这样程序不能实现我要的结果呢。有人问,为什么我又要用局部变量,又多此一举用全局变量,那是因为,diplay()函数需要count 。如果只用局部变量,系统语法会报错count未定义;
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
uchar code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
void display(uint);
void delay(uint);
void num();
uint count ;
void main()
{
TMOD = 0x01;
TH0 = (65535-46080)/256;//50ms
TL0 = (65535-46080)%256;
TR0 = 1;
while(1)
{
num();
display(count);
}
}
void display(uint count)
{
P1 = 0xfe;
P0 = table[count/1000];
delay(2);
P1 = 0xff;
delay(2);
P1 = 0xfd;
P0 = table[count/100%10];
delay(2);
P1 = 0xff;
delay(2);
P1 = 0xfb;
P0 = table[count/10%10];
delay(2);
P0 = 0xff;
delay(2);
P1 = 0xf7;
P0 = table[count%10];
delay(2);
P1 = 0xff;
delay(2);
}
void num()
{
static uint i ;
static uint count=2016;
if(TF0 == 1)
{
TF0 = 0;
TH0 = (65535-46080)/256;//50ms
TL0 = (65535-46080)%256;
i++;
if(count <= 2026)//D?óú2026???′DD????ò????óò?
{
if(i == 20)//i?óò?′?ê?50ms,?tê?′?ê?1s
{
i = 0;//×¢òa?óíêá?òa??àí
count++;
}
}
else //′óóú2026???′DD????ò????ó?t
{
if(i == 40)
{
i = 0;
count++;
}
}
}
}
void delay(uint z)
{
uint x,y;
for(x = z;x>0;x--)
for(y = 110;y>0;y--);
}
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
uchar code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
void display(uint);
void delay(uint);
void num();
uint count ;
void main()
{
TMOD = 0x01;
TH0 = (65535-46080)/256;//50ms
TL0 = (65535-46080)%256;
TR0 = 1;
while(1)
{
num();
display(count);
}
}
void display(uint count)
{
P1 = 0xfe;
P0 = table[count/1000];
delay(2);
P1 = 0xff;
delay(2);
P1 = 0xfd;
P0 = table[count/100%10];
delay(2);
P1 = 0xff;
delay(2);
P1 = 0xfb;
P0 = table[count/10%10];
delay(2);
P0 = 0xff;
delay(2);
P1 = 0xf7;
P0 = table[count%10];
delay(2);
P1 = 0xff;
delay(2);
}
void num()
{
static uint i ;
static uint count=2016;
if(TF0 == 1)
{
TF0 = 0;
TH0 = (65535-46080)/256;//50ms
TL0 = (65535-46080)%256;
i++;
if(count <= 2026)//D?óú2026???′DD????ò????óò?
{
if(i == 20)//i?óò?′?ê?50ms,?tê?′?ê?1s
{
i = 0;//×¢òa?óíêá?òa??àí
count++;
}
}
else //′óóú2026???′DD????ò????ó?t
{
if(i == 40)
{
i = 0;
count++;
}
}
}
}
void delay(uint z)
{
uint x,y;
for(x = z;x>0;x--)
for(y = 110;y>0;y--);
}
首先我要建议小编去看看局部变量和全局变量的定义,看完之后你会明白num函数里定义的static count 本身就是多此一举。你如此定义,程序肯定不对。只要直接在外部定义一个全部变量uint count =2016即可,这样定义的本身就是一个全部的变量而不是局部变量。还有小编的总中断EA =1 没有开