用c++写出判断x是否为水仙花数,若是返回1,不是返回0
时间: 2024-02-28 10:54:56 浏览: 23
好的,以下是用 C++ 编写的水仙花数判断函数:
```c++
int isNarcissistic(int x) {
int sum = 0;
int temp = x;
int n = 0;
while (temp > 0) {
n++;
temp /= 10; // 求出 x 的位数
}
temp = x;
while (temp > 0) {
int r = temp % 10; // 求出 x 的个位
sum += pow(r, n); // 计算每一位的 n 次方之和
temp /= 10;
}
return sum == x; // 判断是否为水仙花数
}
```
在主函数中,可以这样调用:
```c++
int main() {
int x;
cin >> x;
if (isNarcissistic(x)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
```
其中,输入的 x 为待判断的数,isNarcissistic(x) 返回 1 表示 x 是水仙花数,返回 0 表示 x 不是水仙花数。
相关问题
c++判断给定整数是否为水仙花数,是则返回1,否则返回0。
好的,以下是一个C++实现的示例代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int is_narcissistic_number(int num) {
// 获取num的位数
int n = 0, temp = num;
while (temp > 0) {
n++;
temp /= 10;
}
// 求每个位上的数字的n次幂之和
int sum = 0, digit;
temp = num;
while (temp > 0) {
digit = temp % 10;
sum += pow(digit, n);
temp /= 10;
}
// 判断是否为水仙花数
if (sum == num) {
return 1;
}
else {
return 0;
}
}
int main() {
int num;
cout << "请输入一个整数:";
cin >> num;
if (is_narcissistic_number(num)) {
cout << num << " 是水仙花数" << endl;
}
else {
cout << num << " 不是水仙花数" << endl;
}
return 0;
}
```
你可以将这段代码复制粘贴到你的编程环境中运行,也可以根据需要进行修改和优化。
用c++编写,判断参数x是否满足条件,若是则返回1,若不是则返回0
以下是一个简单的 C++ 函数,用于判断参数 x 是否满足条件,若是则返回 1,若不是则返回 0:
```
int check(int x) {
if (/* 判断条件 */) {
return 1;
} else {
return 0;
}
}
```
你需要自己填写判断条件的部分,使其符合你的要求。