使用tolower并存储在数组中

时间:2014-02-14 08:56:51

标签: c arrays for-loop trace tolower

我试图追踪这个问题并且无法弄清楚星是如何通过while循环并存储在数组中。由于tolower,*存储为8?如果有人可以请完成第一个 - 第二个循环请我永远感激。

#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;
}

1 个答案:

答案 0 :(得分: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'的位置)。然后用它来定位数组的元素并递增它,这告诉我们输入了另一个“F”或“f”。

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

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