[题目] 求取值范围内所有满足条件的4位数x,使得x的每位数字的四次方数之和与本身相等。例如:1634=1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 [编程要求] 试建立一个类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。缺省的取值范围是[1000,9999]。 int isdiff(int x):判断参数x是否满足条件,若是返回1,若不是返回0。 void process():求出满足条件的所有x,并将结果存入数组a,同时统计x的个数。 void show():输出数组a及count。 (3)在主函数中完成对该类的测试。定义一个DIF类的对象v,使用1111和9999初始化其下限和上限,按上述要求处理并输出结果。 */ #include<iostream.h> #include<fstream.h> class DIF { int low,high; int a[100]; int count; public: DIF(int lw=1000,int hi=9999) {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(1111,9999); v.process(); v.show(); }
时间: 2024-02-17 13:10:32 浏览: 20
解答如下:
```
#include<iostream>
#include<fstream>
using namespace std;
class DIF {
private:
int low, high;
int a[100];
int count;
public:
DIF(int lw = 1000, int hi = 9999) {
low = lw;
high = hi;
}
int isdiff(int x) {
int sum = 0;
int temp = x;
while (temp != 0) {
int digit = temp % 10;
sum += digit * digit * digit * digit;
temp /= 10;
}
if (sum == x) {
return 1;
}
else {
return 0;
}
}
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 << endl;
//将结果输出到文件"bc02.in"
ofstream outf("bc02.in");
for (int i = 0; i < count; i++)
outf << a[i] << '\t';
outf << '\n';
outf << "count=" << count << endl;
outf.close();
}
};
void main() {
DIF v(1111, 9999);
v.process();
v.show();
}
```