C语言 造成无限循环(*)的循环错误

ojsjcaue  于 2022-12-02  发布在  其他
关注(0)|答案(2)|浏览(206)

这是一个程序,用于查找数组中元素的均值、中值和众数,然后从中制作直方图。
但我的问题只是在星星数和打印星

#include<stdio.h>

int main()
{
    int sample[50] = {4,3,5,5,1,5,5,5,4,3,5,3,3,5,5,5,2,5,5,5,5,4,3,5,5,2,5,2,5,4,3,5,3,3,5,5,5,5,5,5,3,5,4,3,5,3,3,5,5,5,};

    int i;
    int j;
    int f1;
    int f2;
    int f3;
    int f4;
    int f5;
    int temp;
    int sum = 0;
    int count = 0;
    int median;
    float mean;

    for(i = 0; i < count; i++)
    {
    if(sample[i] == 1)
    {
        f1++;
    }
    else if(sample[i] == 2)
    {
        f2++;   
    }
    else if(sample[i] == 3)
    {
        f3++;
    }
    else if(sample[i] == 4)
    {
        f4++;
    }
    else if(sample[i] == 5)
    {
        f5++;
    }
    }
    for(i = 0; i < 5; i++)
    {
        printf("\t%d\t", i + 1);
        if(i == 0)
        {
        printf(" %d\t", f1);
        for(j = 0; j < f1; j++)
        {
            printf("*");
        }
        }
        else if(i == 1)
        {
        printf(" %d\t", f2);
        for(j = 0; j < f2; j++)
        {
            printf("*");
        }
        }
        else if(i == 2)
        {
        printf(" %d\t", f3);
        for(j = 0; j < f3; j++)
        {
        printf("*");
        }
        }
        else if(i == 3)
        {
        printf(" %d\t", f4);
        for(j = 0; j < f4; j++)
        {
            printf("*");
        }
        }
        else if(i == 4)
        {
        printf(" %d\t", f5);
        for(j = 0; j < f5; j++);
        {
            printf("*");
        }
        }
        printf("\n");
    }
return 0;
}

但是,


看起来循环发生是因为数字4的频率是4205314,所以星星循环直到那个数字,但是我不知道为什么频率会那么高

agxfikkp

agxfikkp1#

更简单、更短的方式:

#include <stdio.h>

int main(void) {
    static const int sample[50] = {4,3,5,5,1,5,5,5,4,3,5,3,3,5,5,5,2,5,5,5,5,4,3,5,5,2,5,2,5,4,3,5,3,3,5,5,5,5,5,5,3,5,4,3,5,3,3,5,5,5,};
    int count = sizeof(sample)/sizeof(*sample);    
    int histo[5] = {};
    for(int i=0; i<count; ++i)
    {
        histo[sample[i]-1]++;
    }
    
    char stars[count];
    ((char*)memset(stars, '*', count))[count-1] = '\0';
    
    printf("%-20s%-20s%-20s\n", "Response", "Frequency", "Histogram");
    for(int i=0; i<5; ++i)
    {
        printf("%-20d%-20d%.*s\n", i+1, histo[i], histo[i], stars);
    }

    return 0;
}

输出

Success #stdin #stdout 0s 5500KB
Response            Frequency           Histogram           
1                   1                   *
2                   3                   ***
3                   12                  ************
4                   5                   *****
5                   29                  *****************************
utugiqy6

utugiqy62#

你的大多数变量都是未初始化的,很可能是完全随机的数字。然后你在你的for循环中引用这些随机数字,这就是为什么它们不会像你缩进它们那样表现。
您需要将变量初始化为期望的起始值,例如:

int f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0;

相关问题