若一个三位数等于其各位上数字的立方和,则称这个三位数为水仙花数。例如153是一个水仙花数,因为153=13+53+33.编写一个程序,输出所有的水仙花数,用c语言
时间: 2024-05-08 14:19:42 浏览: 103
很高兴回答您的问题!以下是在C语言中编写的程序,用于输出所有的水仙花数:
```c
#include<stdio.h>
#include<math.h>
int main()
{
int i, j, k, num;
for(i=1; i<=9; i++)
{
for(j=0; j<=9; j++)
{
for(k=0; k<=9; k++)
{
num = i*100 + j*10 + k;
if(num == pow(i,3) + pow(j,3) + pow(k,3))
{
printf("%d\n", num);
}
}
}
}
return 0;
}
```
在该程序中,我们使用了三个for循环来遍历所有的三位数。然后,我们计算出每个数字的立方和,并将其与其原始数字进行比较。如果两者相等,则我们将该数字输出到屏幕上。
希望这对你有所帮助!如果您有更多问题,请随时问我。
相关问题
用c语言编写一个程序,输出所有的水仙花数。若一个三位数等于其各位上数字的立方和,则称这个三位数为水仙花数。例如,153是一个水仙花数,因为
在 C 语言中,我们可以编写一个简单的程序来找出所有的水仙花数。水仙花数是指那些所有位数的立方和等于该数本身的三位数。下面是一个示例程序:
```c
#include <stdio.h>
#include <stdbool.h>
// Function to check if a number is a narcissistic number
bool is_narcissistic(int num) {
int digits[3];
int sum = 0;
// Convert the number into an array of digits
while (num > 0) {
digits[2] = num % 10;
sum += digits[2] * digits[2] * digits[2]; // Calculate cube of each digit
num /= 10;
}
// If the sum equals the original number, it's a narcissistic number
return sum == num;
}
int main() {
int start = 100; // Start from the first three-digit number
int end = 999; // End at the last three-digit number
printf("Narcissistic numbers between %d and %d are:\n", start, end);
for (int i = start; i <= end; i++) {
if (is_narcissistic(i)) {
printf("%d ", i);
}
}
return 0;
}
```
在这个程序中,`is_narcissistic` 函数会检查给定的数是否为水仙花数。`main`函数遍历从100到999的所有三位数,并使用 `is_narcissistic` 进行验证。
若一个三位数等于其各位上数字的立方和,则称这个三位数为水仙花数。例如 153 是一个水仙花数,因为153=1+5+3.编写一个程序,输出所有的水仙花数。实现代码:
为了找到所有的水仙花数,我们可以编写一个简单的循环程序,遍历所有可能的三位数范围,并检查每个数是否满足条件。以下是Python语言的一个示例:
```python
def find_water_lilies():
# 遍历所有三位数,从100到999
for num in range(100, 1000):
# 分离百位、十位和个位
hundreds = num // 100
tens = (num % 100) // 10
ones = num % 10
# 计算每位数字的立方和
sum_of_cubes = hundreds**3 + tens**3 + ones**3
# 如果和等于原数,它是水仙花数
if sum_of_cubes == num:
print(num)
# 执行函数找出水仙花数
find_water_lilies()
```
当你运行上述代码,它将输出所有的水仙花数。
阅读全文
相关推荐















