問題描述
輸出所有的“水仙花數”,所謂的“水仙花數”是指一個三位數其各位數字的立方和等於該數本身,例如153是“水仙花數”,因爲:153 = 13 + 53 + 33。
問題分析
根據“水仙花數”的定義,判斷一個數是否爲“水仙花數”,最重要的是要把給出的三位數的個位、十位、百位分別拆分,並求其立方和(設爲s),若s與給出的三位數相等, 三位數爲“水仙花數”,反之,則不是。
算法設計
“水仙花數”是指滿足某一條件的三位數,根據這一信息可以確定整數的取值範圍是 100〜999。
對代碼的說明:
- 將n整除以100,得出n在百位上的數字hun。
- 將(n-i*100)整除以10(或將n先整除以10再對10求模n/10%10),得出n在十位上的數字ten。
- 將n對10取餘,得出n在個位上的數字ind。
- 求得這三個數字的立方和是否與其本身相等,若相等,則該數爲水仙花數。
用for語句
#include <stdio.h>
#include <math.h>
int main(int argc, const char *argv[])
{
int hun,ten,ind;
int n = 100;
printf("result is:");
for(;n <= 999;n++){
hun = n / 100;
ten = n /10 % 10;
ind = n % 10;
// if (n == hun*hun* hun + ten*ten*ten + ind*ind*ind )
if (pow(hun, 3) + pow(ten, 3) + pow(ind ,3) == n)
printf("%d ",n);
}
printf("\n");
return 0;
}
用while語句
#include <stdio.h>
#include <math.h>
int main(int argc, const char *argv[])
{
int hun, ten, ind;
int n = 100;
printf("result is:");
while(n <= 999){
hun = n / 100;
ten = n /10 % 10;
ind = n % 10;
// if (hun*hun* hun + ten*ten*ten + ind*ind*ind == n )
if (pow(hun, 3) + pow(ten, 3) + pow(ind, 3) == n)
printf("%d ",n);
n++;
}
printf("\n");
return 0;
}
用goto 語句
#include <stdio.h>
#include <math.h>
int main(int argc, const char *argv[])
{
int hun, ten, ind;
int n = 100;
printf("result is:");
_loop:
if(n <= 999){
hun = n / 100;
ten = n /10 % 10;
ind = n % 10;
// if (hun*hun* hun + ten*ten*ten + ind*ind*ind == n )
if (pow(hun, 3) + pow(ten, 3) + pow(ind, 3) == n)
printf("%d ",n);
n++;
goto _loop;
}
printf("\n");
return 0;
}
運行結果
result is:153 370 371 407