0

我试图追踪这个问题,但无法弄清楚星是如何通过 while 循环并存储在数组中的。*是否因为tolower而存储为8?如果有人可以请通过第一个 for - 到第二个 for 循环,我将永远感激不尽。

#include <stdio.h>
#include <ctype.h>

int main()
{
    int index, freq[26], c, stars, maxfreq;

    for(index=0; index<26; index++)
        freq[index] = 0;

    while ( (c = getchar()) != '7')
    {
        if (isalpha(c))
            freq[tolower(c)-'a']++;

        printf("%d", &freq[7]);

    }

    maxfreq = freq [25];
    for (index = 24; index >= 0; index--)
    {
        if (freq[index] > maxfreq)
            maxfreq = freq[index];
    }   

    printf ("a b c d e f\n");

    for (index = 0; index < 5; index++)
    {
        for (stars = 0; stars < (maxfreq - freq[index]); stars ++)
            printf(" ");

        for (stars = 0; stars < (freq[index]); stars++)
            printf("*");

        printf("%c  \n", ('A' + index) );
        printf(" \n");
    }
    return 0;
}
4

1 回答 1

0

这段代码似乎是一种直方图,用于打印给定字符在到达字符“7”之前已输入控制台的次数。

以下代码:

for(index=0; index<26; index++)
    freq[index] = 0;

只是将数组的所有值都设置为 0。这是因为在 C 中,在块范围内(即在函数内部)声明的非静态变量没有特定的默认值因此,只需包含声明变量之前该内存中的垃圾。这显然会影响每次运行时或在其他地方运行时显示的结果,我确定这不是您想要的。

while ( (c = getchar()) != '7')
{
    if (isalpha(c))
        freq[tolower(c)-'a']++;

    printf("%d", &freq[7]);

}

下一节使用 while 循环继续使用 getchar() 接受输入(在这种情况下,它从 STDIN 获取输入的下一个字符),直到到达字符“7”。这是因为分配一个值(例如“c = getchar()”)允许以可以使用“!='7'”比较的方式使用该值。这允许我们继续循环,直到从 STDIN 接受的字符等于 '7',之后 while 循环将结束。

在循环内部,它正在检查使用“isalpha()”输入的值,如果字符是字母,则返回 true。通过使用“tolower()”并返回该值减去“a”的字符值,我们基本上可以找到字母表中的哪个字符是数字的。例如,如果我们采用字母“F”。大写“F”在后台存储为值 70。tolower() 检查它是否是大写字符,如果是,则返回它的小写版本(在本例中,'f' == 102)。然后将该值减去“a”(存储为 97),返回值 6(从 0 开始计数时,是“F”在字母表中的位置)。然后使用它来定位数组的那个元素并增加它,

maxfreq = freq [25];
for (index = 24; index >= 0; index--)
{
    if (freq[index] > maxfreq)
        maxfreq = freq[index];
}

下一节将变量“maxfreq”设置为最后一个值(找到了多少次“Z”),并向下迭代,将 maxfreq 的值更改为找到的最大值(即,任何给定的最大数量在数组中找到的字符)。这稍后用于格式化输出以确保字母正确排列并且星号和空格的数量是正确的。

于 2014-02-14T10:11:20.557 回答