三位的水仙花数: 输入一个三位的正整数n, 输出100~n范围内所有的水仙花数。 用函数判断一个整数是不是水仙花数,是返回1,不是返回0。 主函数调用该函数,实现输出100~n之间的所有水仙花数。 三位的水仙花数是指,该数的三个数字立方之和等于该数本身。
时间: 2024-05-22 13:12:10 浏览: 44
#include <stdio.h>
int isNarcissistic(int n) { // 判断是否为水仙花数
int a = n / 100; // 百位数
int b = n / 10 % 10; // 十位数
int c = n % 10; // 个位数
if (a*a*a + b*b*b + c*c*c == n) { // 判断是否符合条件
return 1; // 是水仙花数,返回1
} else {
return 0; // 不是水仙花数,返回0
}
}
int main() {
int n;
printf("请输入一个三位正整数n:");
scanf("%d", &n);
printf("100~%d范围内的水仙花数有:\n", n);
for (int i = 100; i <= n; i++) { // 遍历100~n的数
if (isNarcissistic(i)) { // 判断是否为水仙花数
printf("%d ", i); // 输出水仙花数
}
}
printf("\n");
return 0;
}
相关问题
C语言:三位的水仙花数: 输入一个三位的正整数n, 输出100~n范围内所有的水仙花数。 用函数判断一个整数是不是水仙花数,是返回1,不是返回0。 主函数调用该函数,实现输出100~n之间的所有水仙花数。
```c
#include <stdio.h>
#include <math.h>
int isNarcissistic(int n);
int main()
{
int n;
printf("请输入一个正整数n:");
scanf("%d", &n);
printf("100~%d范围内的水仙花数有:", n);
for (int i = 100; i <= n; i++)
{
if (isNarcissistic(i))
{
printf("%d ", i);
}
}
return 0;
}
int isNarcissistic(int n)
{
int sum = 0;
int temp = n;
while (temp)
{
int digit = temp % 10;
sum += pow(digit, 3);
temp /= 10;
}
return sum == n;
}
```
c语言 输入一个三位的正整数n, 输出100~n范围内所有的水仙花数。 用函数判断一个整数是不是水仙花数,是返回1,不是返回0。
以下是代码实现:
```c
#include <stdio.h>
#include <math.h>
int isNarcissistic(int num) {
int sum = 0, n = num;
while (n > 0) {
sum += pow(n % 10, 3);
n /= 10;
}
return sum == num;
}
int main() {
int n;
printf("请输入一个三位的正整数:");
scanf("%d", &n);
printf("100~%d范围内的水仙花数有:", n);
for (int i = 100; i <= n; i++) {
if (isNarcissistic(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
```
函数`isNarcissistic`中,先将输入的整数拆分成个位、十位和百位,计算每位的立方和,并与原数比较,判断是否为水仙花数。在主函数中,循环遍历100到输入的整数n,判断每个数是否为水仙花数,是则输出。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)