数组分段求和
假设数组a有1152个数,我想按照顺序每100个数算一个和,求一个平均值,该如何实现?
//假设数组a有1152个数,我想按照顺序每100个数算一个和,求一个平均值,该如何实现? //假设数组a有1152个数,我想按照顺序每100个数算一个和,求一个平均值,该如何实现? #include<stdio.h> #include<time.h> #include <stdlib.h> int main() { int a[1152], i, k, c, s[13] = { 0 }; srand((unsigned int)time(NULL)); for (i = 0, k = 0, c = 0; i < 1152; i++) { a[i] = rand() % 150 + 1; s[k] += a[i]; c++; if (c == 100) { k++; c = 0; } } for (i = 0; i < k; i++){ printf(" %c %d",i==0?'(':'+', s[i]); s[12] += s[i]; } printf(" ) / %d = %d \n",k, s[12] / k); return 0; }
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char c[12][100]; int i, j, sum; memcpy(c, main, 1152); for(i = 0; i < 12; i++) { for(j = 0, sum = 0; j < sizeof(c[i]); j++) sum += c[i][j]; printf("%02d: sum = %d, avr = %d\n", i + 1, sum, sum / 100); } return 0; }
[此贴子已经被作者于2021-9-15 17:34编辑过]
#include <stdio.h> #define N 1152 int main() { int sum = 0; for (int i = 0, j; i < N; i++) { sum += i; j = (i + 1) % 100; if (j == 0 || i == N - 1) { if (j == 0) j = 100; printf("%d / %d = %d\n\n", i, j, sum / j); sum = 0; } else printf("%d + ", i); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { unsigned int num_all,num_one,num_current,group,i,j; float *a,sum; printf("请输入总个数及每组个数:"); scanf("%u %u",&num_all,&num_one); a=malloc(num_all*sizeof(float)); srand((unsigned int)time(NULL)); //模拟数据 for(i=0; i<num_all; i++) *(a+i)=rand(); group=num_all/num_one; if(num_all%num_one!=0) group+=1; for(j=0; j<group; j++) { sum=0; if(j+1==group) { if(num_all%num_one!=0) num_current=num_all%num_one; } else { num_current=num_one; } for(i=0; i<num_current; i++) { sum+=*(a+j*num_one+i); } printf("第%u组和为%.2f,平均值为%.2f\n",j,sum,sum/num_current); } free(a); return 0; }