首页 > 解决方案 > 如何在没有数组的情况下找到输入次数最多的数字?

问题描述

我最近开始阅读一本关于 C 的书并遇到了这个练习。编写一个程序,在不使用数组的情况下读取 100 个整数并输出连续输入次数最多的数字。现在我解决这个问题的方法可能是最愚蠢的。我基本上是“使用一个数组”而不是让它成为一个实际的数组,我必须以艰难的方式做所有事情。有没有更好的方法可以在没有实际数组的情况下做到这一点?提前致谢。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
    int zero, one, two, three ,four,
    five, six, seven, eight, nine;
    int i,j,num,prev = -1;
    
    
    srand(time(NULL));
    for(i=0;i<100;i++){
        num = rand()%10;
        printf("%d\n", num);
        if(num==prev){
            switch(num){
                case 0: zero++;
                case 1: one++;
                case 2: two++;
                case 3: three++;
                case 4: four++;
                case 5: five++;
                case 6: six++;
                case 7: seven++;
                case 8: eight++;
                case 9: nine++;
            }
        }
        prev = num;
    }
    
    num = 0;
    //comparing the number of times of each number
        if(num<zero){
         num=zero;
         j=0;
        }
        if(num<one){
        num=one;
        j=1;
        }
        if(num<two){
         num=two;
         j=2;
        }
        if(num<three){
         num=three;
         j=3;
        }
        if(num<four){
        num=four;
        j=4;
        }
        if(num<five){
         num=five;
         j=5;
        }
        if(num<six){
         num=six;
         j=6;
        }
        if(num<seven){
         num=seven;
         j=7;
        }
        if(num<eight){
         num=eight;
         j=8;
        }
        if(num<nine){
         num=nine;
         j=9;
        }
    printf("Number is %d", j);
    return 0;
}

标签: cloops

解决方案


推荐阅读