gpt4 book ai didi

分割数组并计算重复次数的代码

转载 作者:行者123 更新时间:2023-11-30 17:21:00 25 4
gpt4 key购买 nike

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

#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.");
}
}

最佳答案

修改以下代码段

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

关于分割数组并计算重复次数的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28398987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com