10個小孩分糖果

來源:互聯網
上載者:User

十個小孩圍成一圈分糖果,老師分給第一個小孩10塊,第二個小孩2塊,第三個小孩8塊,第四個小孩22塊,第五個小孩16塊,第六個小孩4塊,第七個小孩10塊,第八個小孩6塊,第九個小孩14塊,第十個小孩20塊。然後所有的小孩同時將手中的糖分一半給右邊的小孩;糖塊數為奇數的人可向老師要一塊。問經過這樣幾次後大家手中的糖的塊數一樣多?每人各有多少塊糖?

#include <stdio.h>#include <stdbool.h>void print(int s[]);bool judge(int c[]);int count=0;//記錄交換的次數int main(){static int sweet[10]={10,2,8,22,16,4,10,6,14,20};//初始化數組資料int i,temp[10],l;printf("                     child\n");printf("round   1   2   3   4   5   6   7   8   9  10\n");printf("---------------------------------------------\n");print(sweet);//輸出每個人手中糖的塊數while(!judge(sweet))//若不滿足要求則繼續進行迴圈{for(i=0;i<10;i++)//將每個人手中的糖分成一半{if(sweet[i]%2==0)//若為偶數則直接分出一半{temp[i]=sweet[i]=sweet[i]/2;//數組temp用於存放孩子給別人的糖數}else//若為奇數則加1後再分出一半{temp[i]=sweet[i]=(sweet[i]+1)/2;}}for(l=0;l<9;l++)//將分出的一半糖給右(後)邊的孩子{sweet[l+1]=sweet[l+1]+temp[l];}sweet[0]+=temp[9];//第十個孩子把糖給第一個孩子print(sweet);//輸出當前每個孩子中手中的糖數}return 0;}bool judge(int c[]){int i;for(i=0;i<10;i++)//判斷每個孩子手中的糖是否相同{if(c[0]!=c[i]){return false;//不相同返回false}}return true;}void print(int s[])//輸出數組中每個元素的值{int k;printf("[%2d]:",count++);for(k=0;k<10;k++){printf("%4d",s[k]);}printf("\n");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.