7-44黑洞數之do while循環

黑洞數也稱爲陷阱數,又稱“Kaprekar問題”,是一類具有奇特轉換特性的數。

任何一個各位數字不全相同的三位數,經有限次“重排求差”操作,總會得到495。最後所得的495即爲三位黑洞數。所謂“重排求差”操作即組成該數的數字重排後的最大數減去重排後的最小數。(6174爲四位黑洞數。)

例如,對三位數207:

第1次重排求差得:720 - 27 = 693;
第2次重排求差得:963 - 369 = 594;
第3次重排求差得:954 - 459 = 495;
以後會停留在495這一黑洞數。如果三位數的3個數字全相同,一次轉換後即爲0。

任意輸入一個三位數,編程給出重排求差的過程。

輸入格式:
輸入在一行中給出一個三位數。

輸出格式:
按照以下格式輸出重排求差的過程:

序號: 數字重排後的最大數 - 重排後的最小數 = 差值
序號從1開始,直到495出現在等號右邊爲止。

輸入樣例:
123

輸出樣例:
1: 321 - 123 = 198
2: 981 - 189 = 792
3: 972 - 279 = 693
4: 963 - 369 = 594
5: 954 - 459 = 495

#include <stdio.h>


int main()
{
	int min,max;
    int i=0,j=1,k=0,l=0;
	int a[3];
	int now=0,num=0;
	int high_lowSort(int a[]);
	int low_highSort(int a[]);
	scanf("%d",&num);
//使用do,while循環更簡潔,故舍棄for循環	 
//	for(i=0;i<3;i++)
//	{
//	 	a[i]=num%10;
//		num=num/10;
//	}
////
//    min=low_highSort(a);
//    max=high_lowSort(a);
////    printf("%d\n",max);
////    printf("%d\n",min);
//    for(j=1;now!=495;j++)
//    {
//    	//1: 321 - 123 = 198
//    	now=max-min;
//    	printf("%d: %d - %d = %d\n",j,max,min,now);
//    	num=now;
//    	for(i=0;i<3;i++)
//			{
//			 	a[i]=num%10;
//				num=num/10;
//			}
//		min=low_highSort(a);
//	    max=high_lowSort(a);
//	}
	do
	{
		//下面這個for循環將所給三位數依次賦給a數組 ,該方法有重複的代碼
		for(i=0;i<3;i++)
			{
			 	a[i]=num%10;
				num=num/10;
			}
		min=low_highSort(a);// 調用函數得最小值 
	    max=high_lowSort(a);// 調用函數得最大值 
	    now=max-min;
    	printf("%d: %d - %d = %d\n",j,max,min,now);
    	num=now;// 再次初始化num 
    	j++;//序號 
			
	}while(now!=495);
    

  return 0;
  
}
//這個函數將所輸入三位數通過數組從大到小排列 
int high_lowSort(int a[3])
    {
        int temp=0;
    	int max=0;
    	if(a[0]<a[1])
    	{
    	   	temp=a[0];
    	   	a[0]=a[1];
    	   	a[1]=temp;
		}
		if(a[1]<a[2])
		{
			temp=a[1];
    	   	a[1]=a[2];
    	   	a[2]=temp;
		}
		if (a[0]<a[1])
		{
			temp=a[0];
    	   	a[0]=a[1];
    	   	a[1]=temp;
		}

		max=a[0]*100+a[1]*10+a[2];//從大到小排列的三位數 
		return max;
	}                   
//這個函數將所輸入三位數通過數組從小到大排列 
int low_highSort(int a[3])
    {
        int temp=0;
    	int min=0;
    	if(a[0]>a[1])
    	{
    	   	temp=a[0];
    	   	a[0]=a[1];
    	   	a[1]=temp;
		}
		if(a[1]>a[2])
		{
			temp=a[1];
    	   	a[1]=a[2];
    	   	a[2]=temp;
		}
		if (a[0]>a[1])
		{
			temp=a[0];
    	   	a[0]=a[1];
    	   	a[1]=temp;
		}
//		int i=0;
//		for(i=0;i<3;i++)
//		{
//			printf("lsat%d ",a[i]);
//		}
		min=a[0]*100+a[1]*10+a[2];//從大到小排列的三位數 ,要細心,一個字符都不能錯 
		return min;
	}                     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章