C/C++/Python实现水仙花数(daffodil)

C/C++/Python实现水仙花数(daffodil)

题目输出100~999中所有的水仙花数。若3位数ABC满足 A B C = A 3 + B 3 + C 3 ABC=A^3+B^3+C^3 ABC=A3+B3+C3,则称其为水仙花数。例如 153 = 1 3 + 5 3 + 3 3 153=1^3+5^3+3^3 153=13+53+33,所以153是水仙花数。

C代码
#include<stdio.h>
#include<math.h>
int main()
{
    
      
	int num ,a,b,c;
	for(num  = 100; num  <= 1000; x++)
	{
    
    
		a = num / 100;   			                        //求解百位a
		b = num / 10 % 10;		                            //求解十位b
		c = num % 10;				                        //求解个位c
		if(num == pow(a,3) + pow(b,3) + pow(c,3))			//水仙花数的公式
			printf("%d\n",num);	//输出
	}
	return 0;
}
Python代码
for num in range(100,1000):
    a = num // 100                              #求解百位a
    b = num // 10%10                            #求解十位b    
    c = num % 10                                #求解个位c
    if num == pow(a,3) + pow(b,3) + pow(c,3):   #水仙花数的公式
        print(num)
C++代码
#include <iostream>
#include <cmath>
using namespace std;
 
int main(int argc, const char * argv[]) {
    
    
    int num, a, b, c;                                  
    
    for(num = 100; num < 1000; n++) {
    
    
        a= n / 10;                                     // 求解百位a
        b = (n / 10) % 10;                             // 求解十位b   
        c= n % 100;                                    // 求解个位c      
        if(num  == pow(x, 3) + pow(y, 3) + pow(z, 3))  // 水仙花数的公式
            cout << n << " ";
    }
    cout << endl;
    return 0;
}

其实解法是一样的,只是各个语言的语法略有差别。
都是先求出个位、十位和百位,然后求立方再相加,刚入门,可能唯一难想的就是怎么求各个位数。

猜你喜欢

转载自blog.csdn.net/fjlaym/article/details/109343977