在c++中水仙花数有哪些
时间: 2024-05-01 17:16:55 浏览: 13
水仙花数是指一个三位数,其各位数字立方和等于该数本身。在C语言中,可以通过循环和条件语句来判断和输出所有的水仙花数,如下所示:
```c
#include <stdio.h>
int main() {
int i, num, sum, digit;
for (i = 100; i < 1000; i++) {
num = i;
sum = 0;
while (num > 0) {
digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if (sum == i) {
printf("%d ", i);
}
}
return 0;
}
```
输出结果为:
153 370 371 407
相关问题
水仙花数c++ 一个n位数
水仙花数是指一个n位数,它的每个位上的数字的n次幂之和等于它本身。在C++中,可以通过循环和取余运算来判断一个数是否为水仙花数。具体实现可以参考以下代码:
```
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n, num, sum, digit;
cout << "请输入一个n位数:";
cin >> n;
num = pow(10, n-1); // 计算n位数的最小值
while (num < pow(10, n)) {
sum = 0;
int temp = num;
while (temp != 0) {
digit = temp % 10;
sum += pow(digit, n);
temp /= 10;
}
if (sum == num) {
cout << num << "是水仙花数" << endl;
}
num++;
}
return 0;
}
```
这段代码可以判断一个n位数是否为水仙花数,并输出所有的水仙花数。其中,使用了pow函数来计算幂次方,使用了循环和取余运算来计算每个位上的数字,并使用了if语句来判断是否为水仙花数。
c++如何求水仙花数
水仙花数是指一个三位数,其各位数字立方和等于该数本身。例如153就是一个水仙花数,因为1^3+5^3+3^3=153。下面是两种C++代码实现水仙花数的方法:
1.使用for循环和if语句:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int a, s, d, f;
for (a = 100; a < 1000; a++) {
s = a % 10;//求出个位
d = (a / 10) % 10;//求出十位
f = a / 100;//求出百位
if (a == s * s * s + d * d * d + f * f * f)
cout << a << " ";
}
cout << endl;
return 0;
}
2.使用while循环和if语句:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n = 100;
while (n < 1000) {
int a = n % 10;//求出个位
int b = (n / 10) % 10;//求出十位
int c = n / 100;//求出百位
if (n == a * a * a + b * b * b + c * c * c)
cout << n << " ";
n++;
}
cout << endl;
return 0;
}