用C语言编程水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。本题要求编写程序,计算所有N位水仙花数。
时间: 2023-11-16 12:06:12 浏览: 91
以下是用C语言编写计算N位水仙花数的程序:
```c
#include <stdio.h>
#include <math.h>
int main() {
int n, start, end, i, j, sum, num;
printf("请输入N的值:");
scanf("%d", &n);
start = pow(10, n - 1); // 计算N位数的最小值
end = pow(10, n) - 1; // 计算N位数的最大值
printf("%d位水仙花数有:\n", n);
for (i = start; i <= end; i++) {
sum = 0;
num = i;
for (j = 0; j < n; j++) {
sum += pow(num % 10, n); // 计算每个位上数字的N次幂之和
num /= 10; }
if (sum == i) {
printf("%d\n", i); // 输出水仙花数
}
}
return 0;
}
```
相关问题
C语言水仙花数是指一个 N位正整数( N≥3),它的每个位上的数字的 N次幂之和等于它本身。 本题要求编写程序,计算所有N位水仙花数。
```c
#include <stdio.h>
#include <math.h>
int main()
{
int n, i, j, sum, num;
scanf("%d", &n); // 输入位数
int start = pow(10, n - 1); // 计算起始数
int end = pow(10, n) - 1; // 计算结束数
for (i = start; i <= end; i++)
{
sum = 0;
num = i;
for (j = 0; j < n; j++)
{
sum += pow(num % 10, n); // 计算每个位数的N次方之和
num /= 10;
}
if (sum == i) // 判断是否为水仙花数
{
printf("%d\n", i);
}
}
return 0;
}
```
--相关问题--:
1. 如何判断一个数是否为质数?
2. 如何在C语言中实
C语言输出水仙花数。输入一个正整数n,输出所有的n位水仙花数
以下是C语言代码,可以输出n位水仙花数:
```c
#include <stdio.h>
#include <math.h>
int main() {
int n, i, j, k, sum;
printf("请输入一个正整数n:");
scanf("%d", &n);
for (i = pow(10, n-1); i < pow(10, n); i++) {
sum = 0;
j = i;
while (j > 0) {
k = j % 10;
sum += pow(k, n);
j /= 10;
}
if (sum == i) {
printf("%d\n", i);
}
}
return 0;
}
```
这个程序会输出所有n位水仙花数,例如输入3,输出的结果为:
```
153
370
371
407
```
相关推荐
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)