有一個8層燈塔,每層的燈數都是上一層的2倍,共有765盞燈。編程求最上層的燈數:
1 #include<stdio.h> 2 #include <math.h> 3 4 int main(int argc, char const *argv[]) 5 { 6 /*pow() 返回值的數據類型為 double*/ 7 8 double c = 0; 9 10 for (int i = 0; i <= 7; ++i) 11 { 12 c += pow(2,i); 13 } 14 15 printf("頂層:%.f\n",765/c); 16 printf("底層:%.f\n",(765/c)*pow(2,7)); 17 return 0; 18 }
分析:
設頂層總共有 x 盞燈 第二層有 x·2^1 盞 第三層有 x·2^2 盞 ......第八層有 x·2^7 盞
共 : x·(2^0+2^1+2^2·····+2^7) = 765 盞
x = 765 / (2^0+2^1+2^2·····+2^7)