【问题标题】:How to check if input array has a number, add 1 to it's corresponding index location in output array?如何检查输入数组是否有数字,将 1 添加到输出数组中对应的索引位置?
【发布时间】: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


【解决方案1】:

您可以使用input[i] 值作为output 数组的索引。但在此之前,您需要检查input[i]是否小于num_vals,以避免越界访问。

   void create_hist(double input[], int num_vals, int output[]) 
    { 
       memset(output, 0, sizeof(int) * 28);
       for(int i = 0; i < num_vals; i++)
       { 
         //You can do as below//
         if(input[i] < num_vals)
         output [input[i]]++;
       } 
    }

【讨论】:

  • 如何演示一些一致的缩进和干净的代码格式。您可以教授 StackOveflow 习俗以及 C.
【解决方案2】:

以下用于生成填充input 数组的值的语句将生成double 值。

x4[i] = (28+1) * ( double ) rand() / RAND_MAX;

它们存储在doubles 的数组中。 由此生成的直方图将是平坦的,因为数组中的每个值都可能是唯一的。这些值必须被截断或四舍五入以获得正确的直方图。

此外,given 的答案将不起作用,因为 double 值被用作数组下标。

if(input[i] < num_vals)
    output [input[i]]++; 

编译将失败,因为input[i]double。 要使上述方法起作用,input 数组的值必须在截断或四舍五入后转换为 int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多