C語言編程題

來源:互聯網
上載者:User
代碼


#include "stdafx.h"
typedef int (* pfun)(int a,int b);
int IsNumberEqual(int number) ;
void ntos (int number, int c[]) ;
void  sort (int a[ ],pfun pf  );
int getmaxn(int a[ ]);
int getminn(int b[ ]);

int asc(int a,int b) {return (a>b?1:0);}
int desc(int a,int b){return (a<b?1:0);}

int main(int argc, char* argv[])
{
    int num=0;
    printf("Please enter a number:");
    scanf("%d",&num);        
    //IsNumberEqual調用時若數不為4位,或有危險,故放最後,短路返回
    while( num<1000 || num>9999 || IsNumberEqual(num) ){
        printf("invalid number :%d,try again:\n",num);
        scanf("%d",&num);
    }    
    int arr[4],max,min;
    do{
        ntos(num,arr);
        max=getmaxn(arr);
        printf("max=%d,",max);
        min=getminn(arr);
        printf("min=%d\n",min);
        num=max-min;
    }while(num!=6174);
    
    printf("\n max(%d)-min(%d)=%d \n",max,min,max-min);
    printf("\ndone");
    return 0;
}
//用函數 int IsNumberEqual(int number) 檢查輸入的整數number各數位是否互不相等,
//有相等傳回值為1否則為0;
int IsNumberEqual(int number) 
{
    int a[4]={0,};
    ntos(number,a);
    int iRes=0;
    for(int i=0;i<4;++i){
        for(int j=i+1;j<4;++j){
            if( a[i]==a[j] ){
                iRes=1;
                break;
            }            
        }
        if(iRes==1)break;
    }
    return iRes;
}

//用函數(void ntos (int number, int c[]) )把四位元整數number各位元碼分別存入數組c
void ntos (int number, int c[]) 
{
    for(int i=0;number>0;++i){
        c[i]=number%10;
        number/=10;
    }
}
//用函數( void  sort (int a[ ] )對4個元素的數組a排序(升序或降序都可以);
void  sort (int a[ ],pfun pf  )
{
    //選擇法
    for(int i=0;i<4;++i){
        for(int j=i+1;j<4;++j){
            if( pf(a[i],a[j]) ){
                int t=a[i];
                a[i]=a[j];
                a[j]=t;
            }
        }
    }
}

//傳回值為最大值
int getmaxn(int a[ ])
{
    int sum=0,pow=1;
    sort(a,desc);
    for(int i=3;i>=0;--i,pow*=10){
        sum+=a[i]*pow;
    }
    return sum;
}
//傳回值為最小值 
int getminn(int a[ ])  
{
    int sum=0,pow=1;
    sort(a,asc);
    for(int i=3;i>=0;--i,pow*=10){
        sum+=a[i]*pow;
    }
    return sum;
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.