您正在尝试在所有单位都被接受之前对出现次数进行计数,除非您为每个值维护一个单独的计数器,否则这是不可能的,如果对输入值范围没有限制或范围是大。
您需要获取所有所有值,然后才能报告任何计数。然后对于数组中的每个值,测试该值是否较早出现,否则,请遍历整个数组以计算出现次数:
#include <stdio.h>
#include <stdbool.h>
int main()
{
// Get number of values
int num = 0 ;
scanf("%d",&num);
// Get all values
int array[25];
for( int i = 0; i < num; i++)
{
scanf("%d",&array[i]);
}
// For each value in array...
for( int i = 0; i < num ; i++)
{
// Check value not already counted
bool counted = false ;
for( int j = 0; !counted && j < i; j++ )
{
counted = array[j] == array[i] ;
}
// If current value has not previously been counted...
if( !counted )
{
// Count occurnaces
int count = 0 ;
for( int j = 0; j < num; j++ )
{
if( array[j] == array[i] )
{
count++ ;
}
}
// Report
printf("%d:%d ",array[i],count);
}
}
return 0;
}
对于您的示例输入,结果为:
5
5 6 6 6 7
5:1 6:3 7:1
可以合并执行counted
和count
评估的两个内部循环:
// Count occurrences of current value,bool counted = false ;
int count = 0 ;
for( int j = 0; !counted && j < num; j++ )
{
if( array[j] == array[i] )
{
count++;
// Discard count if value occurs earlier - already counted
counted = j < i ;
}
}
// If current value has not previously been counted...
if( !counted )
{
// Report
printf("%d:%d ",count);
}
}
本文链接:https://www.f2er.com/3167012.html