代码问题
问题描述
1.程序能够正常运行,在void中运行的blank,number,number,ab始终显示为0;
2.没有弄清楚全局变量到底运用于什么情况?
解决方案
1问题原因:错误定义了全局变量的位置;局部变量(auto变量)在函数结束后会自动释放存储空间,所以一定是0;
2.全局变量运用于那些主函数和子函数都需要且最后需要输出的值,全局变量的意思就是在该系列所有函数都定义了的变量,运行于主程序的完整流程的变量。
切记两点:
(1)全局变量不是在主函数中定义的!!!注意位置
(2)在子函数中不要在额外定义了,全局变量与局部变量冲突且不报错详见错例第一行
ps:不要过分纠结这一块,学完指针啥都明白了。
void friday3(int blank, int number, int other, int ab, char t1[])//形参不能乱定义的
{
int m;
int i;
m = zifushu(t1);
for (i = 0; i < m; i++)
{
if ((t1[i] >= 'a' && t1[i] <= 'z') || (t1[i] >= 'A' && t1[i] <= 'Z'))
ab++;
else if (t1[i] >= '0' && t1[i] <= '9')
number++;
else if (t1[i] == ' ')
blank++;
else
other++;
}
}
# include <stdio.h>
int main(void)
{
char t1[1000];
int blank = 0, number = 0, other = 0, ab = 0;//主函数定义的不是全局变量
gets_s(t1);
void friday3(int blank, int number, int other, int ab, char t1[]);
friday3(blank, number, other, ab, t1);//调用形参单元被释放,实参单元被保留
printf("%d%d%d%d\n", blank, number, ab, other);
return 0pp
下面展示 修正的
。
# include <stdio.h>
int blank,number,other,ab;
void friday3(char t1[])
{
int m;
int i;
for (i = 0; t1[1]!='\0'; i++)//优化写法
{
if ((t1[i] >= 'a' && t1[i] <= 'z') || (t1[i] >= 'A' && t1[i] <= 'Z'))
ab++;
else if (t1[i] >= '0' && t1[i] <= '9')
number++;
else if (t1[i] == ' ')
blank++;
else
other++;
}
int main(void)
{
char t1[1000];
gets_s(t1);
blank = 0, number = 0, other = 0, ab = 0;
void friday3(char t1[]);
friday3(t1);
printf("%d %d %d %d\n", blank, number, ab, blank);
return 0;
}