用于拆分数组并计算重复次数的代码

时间:2015-02-08 20:28:30

标签: c arrays sorting

以下代码几乎可以正常工作,但由于某种原因,打印数组中的第一个值也是最后一个值,也是下一组打印数据的第一个值。我知道这可能听起来令人困惑。 这是代码

#include <stdio.h>
#define MAX 288

int nThArrayPrint(double prev, int count, int i, double *array) {
int j = MAX*i;
for (i = j; i <(j+MAX); i++) {
    if (array[i] == prev) {
        count++;
    } else {
        printf("%.4lf= %d\t", prev, count);
        prev = array[i];
        count = 1;
    }
}
return count;

}

int main()
{
FILE *fp;
fp = fopen("C:\\Users\\niall\\Desktop\\question2.txt", "r");
double array[MAX * 5]; // Initializes array to all 0.0s
int i, x, j, count;
double prev = 0;

if (fp != NULL) {
    for (i = 0; i < MAX * 5; i++) { //Load values from file into an array
        fscanf(fp, "%lf", &array[i]);
    }
    fclose(fp);
    prev = array[0]; // initialize
    for (i = 0; i < 5; i++){
        count = 1;
        printf("\tNumber of times each value is repeated for the %dth set of values\n\n", i+1);
        count = nThArrayPrint(prev, count, i, array);
        prev = array[MAX*i];
         printf("%.4lf= %d\n\n", prev, count);
    }
} else {
    printf("There was a probem opening the file.");
}
}

1 个答案:

答案 0 :(得分:0)

修改代码的以下部分

prev = array[0]; // initialize
for (i = 0; i < 5; i++){
    count = 1;
    printf("\tNumber of times each value is repeated for the %dth set of values\n\n", i+1);
    count = nThArrayPrint(prev, count, i, array);
    prev = array[MAX*i];
     printf("%.4lf= %d\n\n", prev, count);
}

进入

count = 1;
for (i = 0; i < 5; i++){
    printf("\tNumber of times each value is repeated for the %dth set of values\n\n", i+1);
    for (j = i*MAX; j < (i*MAX)+MAX; j++) {
        if (array[j] == array[j+1]) {
            count++;
        } else {
            printf("%.4lf= %d\n", array[j], count);
            count = 1;
        }
    }
    if(count > 1){
        printf("%.4lf= %d\n", array[j], count-1);
        count = 1;
    }
}

使用以下输入进行测试,MAX为9

12 12 12 12 12 1 1 1 1 4 5 5 6 7 8 9 3 3 3 2 2 2 1 1 1 1 1 1 6 62 2.2 2.2 2.2 3.2 3.2 3.2 3.2 22 22 22 22 22 1 22 22 22 22

输出:

    Number of times each value is repeated for the 1th set of values

12.0000= 5
1.0000= 4
    Number of times each value is repeated for the 2th set of values

4.0000= 1
5.0000= 2
6.0000= 1
7.0000= 1
8.0000= 1
9.0000= 1
3.0000= 2
    Number of times each value is repeated for the 3th set of values

3.0000= 1
2.0000= 3
1.0000= 5
    Number of times each value is repeated for the 4th set of values

1.0000= 1
6.0000= 1
62.0000= 1
2.2000= 3
3.2000= 3
    Number of times each value is repeated for the 5th set of values

3.2000= 1
22.0000= 5
1.0000= 1
22.0000= 2