C language practice every day - output the number of daffodils

Question: Please output all the "narcissus numbers"
Solution: The so-called "narcissus number" refers to a 3-digit number, the sum of the cubes of each digit is equal to the number itself.
For example, 153 is the daffodil number because 153 = 1 * 1 * 1 + 5 * 5 * 5 +3 * 3 * 3"

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>


// 编写了个方法(function)
int lifang(int a)
{
	return a * a * a;
}

int main() {
	// 初始化
	int a = 0;
	int b = 0;
	int c = 0;
	// 100 - 1000 中的水仙花数
	for (int i = 100; i < 1000; i++) { // 因为 三位数 是从 100 - 999  然后每次循环 i+1;
		a = i / 100; // 取个位  ;如果 i = 153,i = 1.53,因为是整数,i = 1;
		b = i % 100 / 10; // 取十位;如果 i = 153,i取模然后除,i = 153 % 100 = 53, i = 53 /10 =5.3 = 5;
		c = i % 10; // 取百位 ;如果 i = 153,i取模,i = 153 % 10 = 3;

		// 调用 lifang这个方法,把分别得到的 a,b,c分别放到里面,进行立方然后相加最后等于它本身
		if (lifang(a) + lifang(b) + lifang(c) == i) {
			printf("%d\n", i); // 如果等于它本身 就打印,不等于它就不打印;
		}
		
	}
	return 0;
}

The running result is:

 Problem-solving idea: Cubing is the cube of a single digit. Split the three digits, assign a value each time after splitting, then cube each digit, and then output it.

Guess you like

Origin blog.csdn.net/m0_58724783/article/details/131921433