[题目] 求取值范围内所有满足条件的x,使得x的每位数字的立方和与本身相等。
[编程要求]
试建立一个类DIF,完成求出某个范围内的所有满足条件的x,以及x的个数。
具体要求如下:
(1)私有数据成员。
int low,high:x的取值范围的下限和上限。
int a[100]:存放满足要求的x.
int count:满足条件的x的个数。
(2)公有成员函数
DIF(int lw,int hi):构造函数,用参数lw和hi分别初始化low和high。缺省的取值范围是[10,1000]。
int isdiff(int x):判断参数x是否为水仙花数,若是返回1,若不是返回0。
void process():求出满足条件的所有x,并将结果存入数组a,同时统计x的个数。
void show():输出数组a及count。
(3)在主函数中完成对该类的测试。定义一个DIF类的对象v,使用100和999初始化其下限和上限,按上述要求处理并输出结果。
*/
#include<iostream.h>
#include<fstream.h>
class DIF
{
int low,high;
int a[100];
int count;
public:
DIF(int lw=10,int hi=1000)
{low=lw;high=hi;}
int isdiff(int x)
{
/********** Begin **********/
/********** End **********/
}
void process()
{
count=0;
for(int x=low;x<=high;x++)
{
if(isdiff(x))
a[count++]=x;
}
}
void show()
{ for(int i=0;i<count;i++)
cout<<a[i]<<'\t';
cout<<'\n';
cout<<"count="<<count;
//此处将结果输出到文件"bc02.in",请勿改动,否则影响判分
ofstream outf("bc02.in");
for( i=0;i<count;i++)
outf<<a[i]<<'\t';
outf<<'\n';
outf<<"count="<<count;
outf.close();
}
};
void main()
{ DIF v(100,999);
v.process();
v.show();
}
int isdiff(int x)
{
int sum = 0;
int temp = x;
int numDigits = to_string(x).length();
while (temp != 0)
{
int digit = temp % 10;
sum += pow(digit, numDigits);
temp /= 10;
}
if (sum == x)
return 1;
else
return 0;
}
在isdiff()函数中,可以使用循环提取其每一位的数字,将每一位数字的立方和累加和中,循环结束再判断这个立方和是否等于其本身,如果等于则返回1,否则返回0即可。
补充如下:
参考链接:
#include<iostream>
#include<fstream>
using namespace std;
class DIF
{
int low,high;
int a[100];
int count;
public:
DIF(int lw=10,int hi=1000)
{low=lw;high=hi;}
int isdiff(int x)
{
/********** Begin **********/
int sum=0,temp;
int same=x; // 备份x
while(x!=0){ // 从x中逐步提取每一位的数字,直到x为0
temp=x%10; //提取个位
sum+= temp*temp*temp; // 将个位的立方累加到和sum中
x/=10; // x除以10,以便下次循环提取与计算其下一位的数字
}
// https://baike.baidu.com/item/%E6%B0%B4%E4%BB%99%E8%8A%B1%E6%95%B8/2746160
if(sum==same){ // 如果原x的每位数字的立方和等与其本身,则返回1
return 1;
}else{ // 否则返回0
return 0;
}
/********** End **********/
}
void process()
{
count=0;
for(int x=low;x<=high;x++)
{
if(isdiff(x))
a[count++]=x;
}
}
void show()
{ for(int i=0;i<count;i++)
cout<<a[i]<<'\t';
cout<<'\n';
cout<<"count="<<count;
//此处将结果输出到文件"bc02.in",请勿改动,否则影响判分
ofstream outf("bc02.in");
for( int i=0;i<count;i++)
outf<<a[i]<<'\t';
outf<<'\n';
outf<<"count="<<count;
outf.close();
}
};
int main()
{ DIF v(100,999);
v.process();
v.show();
}
class DIF:
def __init__(self, lw=10, hi=1000):
self.low = lw
self.high = hi
self.a = []
self.count = 0
def is_diff(self, x):
num_str = str(x)
digit_sum = sum(int(digit)**3 for digit in num_str)
if digit_sum == x:
return 1
else:
return 0
def process(self):
self.a = [x for x in range(self.low, self.high+1) if self.is_diff(x)]
self.count = len(self.a)
def show(self):
print("满足条件的数: ", self.a)
print("满足条件的数的个数: ", self.count)
# 创建DIF对象v,并使用100和999初始化其下限和上限
v = DIF(100, 999)
# 调用process方法求出满足条件的所有x,并将结果存入数组a,同时统计x的个数
v.process()
# 调用show方法输出结果
v.show()
满足条件的数: [153, 370, 371, 407] 满足条件的数的个数: 4