使用函数输出水仙花数:输入两个正整数m和n(1≤m、n≤l 000),输出m-n之间的所有满足各位数字的立方和等于它本身的数。要求定义并调用函数is( number)判断umber的各位数字之立方和是否等于它本身、试编写相应程序。
时间: 2023-05-13 08:07:18 浏览: 89
以下是使用 Lua 编写的程序,可以输出 m-n 之间的所有水仙花数:
function is(number)
local sum = 0
local temp = number
while temp > 0 do
local digit = temp % 10
sum = sum + digit * digit * digit
temp = math.floor(temp / 10)
end
return sum == number
end
function printNarcissisticNumbers(m, n)
for i = m, n do
if is(i) then
print(i)
end
end
end
printNarcissisticNumbers(100, 999)
注意:这个程序只是一个简单的示例,可能存在一些性能问题,比如在判断每个数字是否为水仙花数时,每次都需要重新计算各位数字的立方和。实际上,可以使用一些优化技巧来避免重复计算,提高程序的效率。
相关问题
使用函数输出水仙花数:输入两个正整数m和n,100<=m<n<=999
题目描述:水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。输入两个正整数m和n(100≤m≤n≤10000),输出开区间(m,n)内所有的水仙花数。本题要求编写两个函数,一个判断给定整数是否水仙花数,另一个按从小到大的顺序打印出给定区间内所有的水仙花数。要求定义并调用函数narcissistic(number)判断number是否为水仙花数,是则返回1,否则返回0。定义并调用函数print_n(m,n)按从小到大的顺序输出区间(m,n)内所有的水仙花数。
```c
#include <stdio.h>
#include <math.h>
int narcissistic(int num) {
int num_ = num, count = 0, sum = 0, ev;
int num__ = num;
do {
count++;
num /= 10;
} while (num);
do {
ev = num_ % 10;
sum += pow(ev, count);
num_ /= 10;
} while (num_);
if (sum == num__) return 1;
else return 0;
}
void print_n(int m, int n) {
int i;
for (i = m + 1; i < n; i++) {
if (narcissistic(i)) {
printf("%d\n", i);
}
}
}
int main() {
int m, n;
scanf("%d%d", &m, &n);
print_n(m, n);
return 0;
}
```
用c语言使用函数输出水仙花数:输入两个正整数m和n(1≤m、n≤l 000),输出m-n之间的所有满足各位数字的立方和等于它本身的数。要求定义并调用函数is( number)判断umber的各位数字之立方和是否等于它本身、试编写相应程序。
以下是用 C 语言编写的程序,可以输出 m-n 之间的所有水仙花数:
```c
#include <stdio.h>
int is(int number);
int main() {
int m, n, i;
printf("请输入两个正整数 m 和 n(1≤m、n≤1000):");
scanf("%d %d", &m, &n);
printf("m-n之间的所有水仙花数为:\n");
for (i = m; i <= n; i++) {
if (is(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
int is(int number) {
int sum = 0, temp = number;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
return sum == number;
}
```
如果您有任何关于这个程序的问题,欢迎随时问我。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)