我有一个程序,需要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;
}
答案 0 :(得分:1)
看起来非常直接,除非我错过了这一点(完全可能)。怎么样:
for(int i = 0; i < people; i++)
{
// Set person to work on
for(int j = 0; j < sample; j++)
{
//process numbers
}
}
或者你可以移动循环以使外部成为样本而内部成为人。
答案 1 :(得分:1)
使用两个数组,即int sample[25][20]
,并使用两个嵌套for
来处理整个数组。你当然可以将这样的数组传递给一个函数。查看一个好的C教程,比如ones by Steve Summit。是的,它们已经很老了,但仍然相关。更现代的方法是here。
答案 2 :(得分:0)
同意海报说这可以用一个阵列来处理。请原谅随机数据生成位:
#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 )));
}