作业帮 > 综合 > 作业

用C++面向对象的方法和对象数组方法来验证卡布列克运算

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/07/09 02:14:21
用C++面向对象的方法和对象数组方法来验证卡布列克运算
给定任意一个四位整数 N(N>0),其各位数字不完全相同.这个数必有这样的规律:
1) 把组成 N 的四个数字从小到大排列,构成最小四位数 min ;
2) 把组成 N 的四个数字从大到小排列,构成最大四位数 max ;
3) 然后求 max 与 min 之差,得到一个新的四位数 ;
重复以上过程,最后总能得到结果:6174.要求本题采用面向对象的方法和对象数组来完成来完成.
举例:4321-1234=3087;8730-0378=8352;8532-2358=6174;……
C lass NB{
int n ,max ,min ,max_min; // n为任意一个四位整数.
public:
NB( ){
min=max=max_min=0;
}
int operating (int );//run the process to validate 6174; result=6174?1;0
void display( );//show max;min;max_min;
};
int main( ){
int count=0 ;
NB nb[200] ; // 建立对象数组;
for( int i=1000; i
#include<iostream>
#include<algorithm>
using namespace std;
class NB{
int n , max , min , max_min; // n为任意一个四位整数.
public:
NB(){
min=max=max_min=0;
}
int  operating  (int );//run the process to validate 6174;  result=6174?1;0
void display();//show max;min;max_min;
};
int NB::operating(int i)
{
    n=i;
    int a=i/1000;
    int b=i%1000/100;
    int c=i%100/10;
    int d=i%10;
    if(a!=b && a!=c && a!=d && b!=c && b!=d && c!=d)
        return 1;
    return 0;
}
void NB::display()
{
    int a[4],i;
    while(n!=6174)
    {
    for(i=0;i<4;i++)
        a[i]=n%10,n/=10;
    sort(a,a+4);
    for(i=0;i<4;i++)
    {
        min=min*10+a[i];
        max=max*10+a[3-i];
    }
    max_min = max - min;
    n = max_min;
    cout<<max<<"-"<<min<<"="<<max_min<<" ";
    min = max =0;
    }
    cout<<endl;

}
int main( ){
int count=0 ;
NB nb[200] ; // 建立对象数组;
for( int i=1000; count<200 && i<10000;i++){
if(nb[count].operating (i)!=0) {nb[count].display();count++;}
//else {cout<<"Err!"; break;}
}
return 0;
 }