一道C语言编程题,请看看我的代码哪里有问题,输出是无限循环。 50
#include<stdio.h>#include<stdlib.h>#defineN20intjudge(inta[],intn)/*判断每个孩子手中的糖果是否一样多*...
#include <stdio.h>#include <stdlib.h>#define N 20 int judge (int a[ ], int n) /* 判断每个孩子手中的糖果是否一样多 */ { int i; for (i = 1; i < n; i++) if (a[0] != a[i]) return 0; else return 1;} int kid[N], aftadjust[N];void main(){ int i, n, teacheradd, times; printf("请输入幼儿园里有多少个孩子\n"); scanf("%d", &n); printf("请输入孩子们一开始各自都有多少糖\n"); for (i = 0; i < n; i++) { scanf("%d", &kid[i]); printf("第%d名孩子手上一开始有%d颗糖\n", i+1, kid[i]); } teacheradd = 0; times = 0; while (!judge(kid,n)) /*调整孩子们手中的糖果数量*/ { times++; for (i = 0; i < n; i++) { if (kid[i] % 2) { kid[i]++; teacheradd++; } if (i < n - 1) aftadjust[i + 1] = kid[i] / 2; else { aftadjust[0] = kid[i] / 2; kid[i] /= 2; } for (i = 0; i < n; i++) kid[i] += aftadjust[i]; } printf("一共调整了 %d 次\n", times); printf("最后每个孩子都有 %d 颗糖果\n", kid[0]); printf("调整过程中老师新增发了%d 颗糖果。\n", teacheradd); } system("pause");}
展开
2个回答
展开全部
#include <stdio.h>
#include <stdlib.h>
#define N 20
bool judge (int a[ ], int n) /* 判断每个孩子手中的糖果是否一样多 */
{
int i;
for (i = 1; i < n; i++)
if (a[0] != a[i]) return 0;
return 1;
}
void print(int src[],int n){
for(int i=0;i<n;i++){
printf("%d ",src[i]);
}
printf("\n");
}
int main(){
int kid[N], aftadjust[N];
int i, n, teacheradd, times;
printf("请输入幼儿园里有多少个孩子\n");
scanf("%d", &n);
printf("请输入孩子们一开始各自都有多少糖\n");
for (i = 0; i < n; i++) {
scanf("%d", &kid[i]);
printf("第%d名孩子手上一开始有%d颗糖\n", i+1, kid[i]);
}
teacheradd = 0;
times = 0;
while (!judge(kid,n)) /*调整孩子们手中的糖果数量*/
{
times++;
for (i = 0; i < n; i++) {
if (kid[i] % 2) {
++kid[i]; teacheradd++;
}
aftadjust[i]=kid[i]/2;
}
for(i=0;i<n;i++){
if(i==n-1){
kid[0]=kid[0]/2+aftadjust[i];
continue;
}
kid[i+1]=kid[i+1]/2+aftadjust[i];
}
//print(kid,n);
}
printf("一共调整了 %d 次\n", times);
printf("最后每个孩子都有 %d 颗糖果\n", kid[0]);
printf("调整过程中老师新增发了%d 颗糖果。\n", teacheradd);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询