Problem E: 求最大值和最小值
阿新 • • 發佈:2019-02-05
Description
求出一些整數中的最大值和最小值。
Input
輸入為多行,以EOF結束。每行為一個十進位制的數字,全部由0~9組成,每行最長不超過1000個字元。有些數字會以0開頭(不影響數值大小的前導0)。
Output
輸出為輸入中的最大值和最小值,格式見sample。
Sample Input
02010001201223Sample Output
The maximum value is : 23The minimum value is : 2HINT
由於輸入已經超過64bit整數的數值上限,因此應該用字串把輸入儲存下來,進行大小的判斷。
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char max[2000]; char min[2000],temp[2000]; int flag=1; int m,n; int low,high; while(scanf("%s",temp)!=EOF){ m=strlen(temp); n=0; for(n=0;temp[n]=='0'&&n<m;n++); m-=n; //求出第一非0位置 if(m==0){ temp[0]='0'; temp[1]=0; n=0; }//如果輸入的字串為全0 if(flag==1){ strcpy(max,&temp[n]); strcpy(min,&temp[n]); low=m; high=m; flag=0; }//第一輪進入後使其變為最大最小字串均為進入的字串 if(m<low){ low=m; strcpy(min,&temp[n]); } if(m>high){ high=m; strcpy(max,&temp[n]); }//長度大於或小於直接交換 if(m==low){ if(strcmp(&temp[n],min)<0){ strcpy(min,&temp[n]); } } if(m==high){ if(strcmp(&temp[n],max)>0) strcpy(max,&temp[n]); } } printf("The maximum value is : %s\n",max); printf("The minimum value is : %s\n",min); return 0; }