繁体   English   中英

是否可以在C编程中使用for循环运行多个数组/变量?

[英]Is it possible to have a for loop run through multiple arrays/variables in C programming?

我有一个程序,需要25个人的20个样本,然后必须将该样本中的每个数字与百分比相关联。

有没有办法通过一个函数创建一个for循环,它将遍历所有样本而不用我手动完成它?

恩。

int sample1[20]={1,2...20};
...
int sample25[20]={1,7..97};

我有一个for循环通过其中一个数组,并将它与一个500个数字的更大数组相关联。 我需要知道是否有办法运行sample1然后是2,然后是3等。没有我手动进入函数并放入一个新数组。

或者你可以发送一个数组到一个函数?

    #include <stdio.h>

int main()
{
int x;
float valid,mean,total=0;


for (x = 0;x < 20; x++)
{
    float percent[500]={4.268,  4.014,  3.905,  3.853,  3.765,  3.949,  3.832..etc};
    int sample1[20]={66,20,221,321,...};


    sample1[x];
    valid=percent[sample1[x]-1];

    printf("\n%d = %.3f",sample1[x],percent[sample1[x]-1]);

    total= total+ percent[sample1[x]-1];
}
    mean= total/20;
    printf("\n\nThe mean percentage for the sample is %.3f",mean);

return 0;
}

看起来非常直接,除非我错过了这一点(完全可能)。 怎么样:

for(int i = 0; i < people; i++)
{
    // Set person to work on
    for(int j = 0; j < sample; j++)
    {
        //process numbers
    }
}

或者你可以移动循环以使外部是样本而内部是人。

使用两dimentsional阵列,即int sample[25][20]并使用两个嵌套for处理整体。 你当然可以将这样的数组传递给一个函数。 查看一个很好的C教程,就像Steve Summit那样 是的,它们已经很老了,但仍然相关。 这里有一种更现代的方法。

同意海报说这可以用一个阵列处理。 请原谅随机数据生成位:

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

#define DATA_SIZE  500
#define NUM_PEOPLE  25
#define NUM_SAMPLES 20

float random_samples[DATA_SIZE] = {};

void create_random_samples();
float calculate_average( float *arr, int size );
float random_i_to_j( float i, float j );

int main()
{
    float sample_average[NUM_SAMPLES] = {};

    int i, j;
    for ( i = 0; i < NUM_PEOPLE; i++ ) {
        for ( j = 0; j < NUM_SAMPLES; j++ ) {
            create_random_samples();
            sample_average[j] = calculate_average( random_samples, DATA_SIZE );
        }
    }

    for ( i = 0; i < NUM_PEOPLE; i++ ) {
        for ( j = 0; j < NUM_SAMPLES; j++ ) {
           printf( " person: %d sample: %d sample average: %.2f \n", i, j, sample_average[j] );
        }
    }
    return 0;  
}

void create_random_samples( int num )
{
    int i;
    for ( i = 0; i < DATA_SIZE; i++ ) {
        random_samples[i] = random_n_to_m( 2.00, 5.00 );  // random samples between 2.00 and 5.00
    }
}

float calculate_average( float *arr, int size )
{
    float average = 0;
    float total = 0;
    int i;
    for ( i = 0; i < size; i++ ) {
        total += arr[i];
    }
    average = total / size;
    return average;
}

float random_i_to_j( float i, float j )
{
    return i + ( rand() / ( RAND_MAX / ( j - i )));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM