【发布时间】:2018-08-19 05:45:55
【问题描述】:
对于一个类,我们需要编写一小段代码来检查输入数组中是否有数字,如果该数字存在,它将 +1 到输出数组的索引位置。示例:
输入:
1
1
3
2
输出
0 2 1 1
在这种情况下,有 2 个数字 1,因此在输出的索引位置 1 处为 +2。我只是不知道该怎么做?这是我目前所拥有的。
#include <stdarg.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <math.h>
void create_hist(double input[], int num_vals, int output[]) {
memset(output, 0, sizeof(int) * 28);
for(int i = 0; i < num_vals; i++){
//HERE IS WHERE I AM STUCK//
}
}
}
void call_function( const char * label, double x[], int count ) {
int hist[28 + 1];
create_hist( x, count, hist );
printf( "%s\n", label );
printf( "\tInput data:\n" );
for ( int i = 0; i < count; i++ ) {
printf( "\t%d\t%f\n", i, x[i] );
}
printf( "\tHistogram:\n" );
for ( int i = 0; i <= 28; i++ ) {
printf( "\t%d\t%d\n", i, hist[i] );
}
printf( "\n" );
}
int main( void ) {
srand( time( NULL ) );
double x1[] = { 0 };
call_function( "Count == 0", x1, 0 );
double x2[] = { 0, 0, 0 };
call_function( "Three equal values", x2, 3 );
double x3[28 + 1];
for ( int i = 0; i <= 28; i++ ) {
x3[i] = i;
}
call_function( "One value in each bucket", x3, 28 + 1 );
double x4[28 * 2 + 1];
for ( int i = 0; i <= 28 * 2; i++ ) {
x4[i] = (28+1) * ( double ) rand() / RAND_MAX;
}
call_function( "Random values", x4, 28 * 2 + 1 );
return 0;
}
【问题讨论】:
-
为什么示例输出的第一个元素有一个
0?我希望它像其他人一样拥有1。 -
@chrisaycock 读起来就像您在提供的示例数据中看到了“0”。我没有。
标签: c arrays list indexing position