用c语言编写分糖果问题!
10个小孩围成一圈分糖果,老师顺次分给每个人的糖块数为12,2,8,22,16,4,10,6,14,20。然后按下列规则调整,所有小孩同时把自己的糖果分一半给右边的小孩,糖块数变为奇数的人,再向老师补要一块,问经过多少次调整后,大家的糖块一样多,且每人多少块。学的还比较少,希望大家回复的时候可以尽量易懂!
(结帖)
[此贴子已经被作者于2017-5-7 10:03编辑过]
#include <stdio.h> int main(void) { int Children[10] = { 12,2,8,22,16,4,10,6,14,20 }; int tmp[10]; for (int n=1;;n++) { for (int i = 0; i < 10; i++) { tmp[i] = Children[i] / 2; //把每人手中的糖减去一半,并存放到tmp数组待用 Children[i] = tmp[i]; } for (int j = 0; j < 10; j++) //把糖分给右边的人 { if (j == 0) Children[j] += tmp[9]; else Children[j] += tmp[j - 1]; } for (int k = 0; k < 10; k++) //手上糖为单数的,+1成双数 if (Children[k] % 2 == 1) Children[k] += 1; for (int y = 0; y < 10; y++) printf("%d ",Children[y]); printf("\n"); for (int x = 0; x < 10; x++) { if (Children[0] != Children[x]) //对比每人手中糖果数,有不同则跳出循环从头继续 break; if (x == 9) //经过10次对比相同,则输出并结束程序 { printf("经过 %d 次调整后,大家的糖块一样多,且每人 %d 块。\n", n, Children[0]); return 0; } } } return 0; }
#include <stdio.h> #include <stdbool.h> bool foo( unsigned a[10], unsigned b[10] ) { bool bchanged = false; for( size_t i=0; i!=10; ++i ) { b[i] = (a[(i+9)%10]/2 + a[i]/2 + 1)/2*2; bchanged = a[i]==b[i]?bchanged:true; } return bchanged; } int main( void ) { unsigned buf[2][10] = { 12,2,8,22,16,4,10,6,14,20 }; unsigned count = 0; for( ; foo(buf[count%2],buf[(count+1)%2]); ++count ) { //printf( "count=%-3u ", count+1 ); //for( size_t i=0; i!=10; ++i ) // printf( "%3u%c", buf[(count+1)%2][i], " \n"[i+1==10] ); } printf( "count=%u, number=%u\n", count, buf[0][0] ); return 0; }