调用函数fun判断一个三位数是否是\"水仙花数\"。在main函数中从键盘输入一个三位数,并输出判断结果。请编写fun函数。所谓\"水仙花数\"是指一个3位数,其各位数字立方和等于该数本身。例如,153是一个
时间: 2023-04-13 22:04:27 浏览: 67
水仙花数,因为1^3 + 5^3 + 3^3 = 153。
以下是fun函数的代码:
bool fun(int num) {
int digit1 = num / 100; // 获取百位数字
int digit2 = (num / 10) % 10; // 获取十位数字
int digit3 = num % 10; // 获取个位数字
int sum = digit1 * digit1 * digit1 + digit2 * digit2 * digit2 + digit3 * digit3 * digit3; // 计算立方和
return sum == num; // 判断是否为水仙花数
}
在main函数中,可以这样调用fun函数:
int main() {
int num;
cout << "请输入一个三位数:";
cin >> num;
if (fun(num)) {
cout << num << "是水仙花数。" << endl;
} else {
cout << num << "不是水仙花数。" << endl;
}
return ;
}