练习1-8
#include <stdio.h>
int main(void)
{
int c, i, nwhite, nother;
nwhite = nother = 0;
int ndigit[10] = { 0 };
while ((c = getchar()) != EOF)
{
if (c >= '0' && c <= '9')
++ndigit[c - '0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits = ");
for (i = 0;i<10; ++i) {
printf("%d", ndigit[i]);
}
printf("空格%d,other%d\n", nwhite, nother);
}
return 0;
}
练习1-13 水平方向
#include <stdio.h>
int main()
{
int longth, valong = 0; // 变量 longth 用于存储输入的字符,变量 valong 用于计算单词长度
int array[20] = { 0 }; // 数组 array 用于记录单词长度为 1-20 的出现次数,初始化为 0
while ((longth = getchar()) != EOF) // 循环读取输入
{
if (longth != '\n') { // 如果不是换行符,单词长度加 1
++valong;
}
else { // 如果是换行符,记录此长度的单词出现次数,valong 重置为 0
++array[valong];
valong = 0;
}
}
for (int i = 0; i < 20; i++) { // 循环输出每个单词长度对应的出现次数
int s = 0; // 变量 s 用于记录当前长度的单词出现次数
printf("%02d:", i + 1); // 输出当前长度
if (array[i + 1] > 0) { // 如果有出现次数,输出对应数量的星号
for (s = 0; s < array[i + 1]; s++) {
printf("* ");
}
}
if (s > 0) // 如果有出现次数,输出该数量
printf("%d", s);
printf("\n"); // 换行
s = 0; // 重置 s 的值
}
return 0;
}