6.20
(1)
#include <stdio.h>
/* count digits, white space,others */
int main()
{
int c,i,nwhite,nother;
int ndigit[10];
nwhite = nother = 0;
for(i = 0; i < 10; i++)
ndigit[i]=0;
while ((c=getchar()) != EOF) {
if ((c == ' ') || (c == '/t') || (c == '/n'))
++nwhite;
else if ((c >= '0') && (c <= '9'))
++ndigit[c - '0'];
else
++nother;
}
printf("%d,%d,",nwhite,nother);
for(i = 0; i < 10; i++)
printf("%d,",ndigit[i]);
return 0;
}
Notice: here is a smart expression!
if ((c >= '0') && (c <= '9'))
++ndigit[c - '0'];
(2)
In C, all function arguments are passed “by value”. The called function cannot directly alter a variable in the calling function; it can only alter its private, temporary copy.
When necessary, it is possible to arrange for a function to modify a variable in a calling routine, the called function must declare the parameter to be a pointer and access the variable indirectly through it.
The story is different for arrays.
Automatic variables:
Come and go with function invocation (include main ()), they do not retain their values from one call to the next, and must be explicitly set upon each entry. If they are not set, they will contain garbage.
External variables:
Remain in existence permanently; retain their values even after the functions that set them have returned. It must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context.
“Definition”: refers to the place where the variable is created or assigned storage.
“Declaration”: refers to places where the nature of the variable is stated but no storage is allocated.
ok!
本文介绍了一个简单的C语言程序,用于统计输入文本中的数字、空白字符和其他字符的数量。此外,还探讨了C语言中参数传递的方式及变量的作用域,包括自动变量和外部变量的区别。

被折叠的 条评论
为什么被折叠?



