c - 如何在没有数组的情况下找到输入次数最多的数字?
问题描述
我最近开始阅读一本关于 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;
}
解决方案
推荐阅读
- mongodb - Mongodb 查询以自午夜以来的秒数计算和比较时间
- java - 从 JSON 响应中获取数组列表
- c# - 如何在datagridview C#中将字符串值设置为整数单元格
- azure-data-explorer - 如何从 Kusto 日期时间中去除秒和毫秒
- javascript - 使用 MongoJs 找不到记录
- c# - 如何使用 Visual Studio 设置 Windows 窗体应用程序的默认文本输入状态?
- r - Python相当于dplyr的summary
- javascript - 用 promise 监听 firestore 快照的变化
- r - 将数据从 yyyyMM 转换为 yyyyQQ
- python - 想知道如何将第一个字母大写,如果不大写会出错