答案:
#include <stdio.h>
int main()
{int n = 0, m = 0, j = 0, s = 0, count1 = 0,k=0;int arr[101] = { 0 }; //选择数组是用来控制打印格式while (scanf("%d%d", &n, &m) == 2 && (n <= 100 && n>0)) //多组数据输入{int sum = 0;int count = 0;int i = 2, t = 0;for (t = 1; t <= n; i += 2, t++) //2的递增数列{sum += i; count++; //该数组器用来控制2的递增次数if (count == m) //如果此时次数满足输入要求的每m个数就计算平均值{count1++; //该计数器用来控制数组下标s = sum / count; //s是平均值arr[count1] = s; //将平均值存在数组里sum = 0; //每满m个数就清零count = 0; //每满m个数就清零}if (t == n && count!=0) //如果循环到最后一个数,但此时没满m个数(即存在数字,但这些数字不够凑一组){count1++; //将这几个不够一组的数字的平均值存在数组里s = sum / count;arr[count1] = s;}}for (j = 1; j <= count1; j++) //从数组下标1开始打印{printf("%d", arr[j]);if (j != count1) //如果不是最后一个数就打空格printf(" ");else //如果是最后一个数就不打空格,直接换行printf("\n");}for (k = 0; k <= count1; k++) //再次通过循环将数组清空,变为初始数组{arr[k] = '0';}count1 = 0; //下标计数器也清零,为下一组数据做准备}return 0;
}
难点:打印到最后一个的值后面会多打印一个空格,普通循环打印无法控制第几次打印的格式,因为缺少一个变量,所以改用数组来控制打印格式