本題很簡單,但是先容我吐槽一會兒,如果用while(~scanf("%d",&n))反而會輸出超限。。。笑死我了。。。。
1127: 【C語言程序設計】[7.4.2]最大元素 [水題]
時間限制: 1 Sec 內存限制: 128 MB提交: 257 解決: 72 統計
題目描述
編一個程序,讀入n個元素的實型數組,然後調用一個函數,遞歸地找出其中的最大元素,並指出它的位置。
輸入
第一行是一個整數n(0<n<1000),代表元素的個數。
第二行是n個以一個空格分開的實數(保證無相等元素)。
輸出
輸出最大元素(保留三位小數)及它在數組中出現的位置。
樣例輸入
3
2.0 3.1 4.3
樣例輸出
4.300 2
遞歸代碼:
#include<cstdio>
int search(float *A,int n)
{
if(n==1) return 0;
int tem=search(A+1,n-1);
return A[0]>A[tem+1]?0:tem+1;
}
int main()
{
int t;
float a[1005];
scanf("%d",&t);
for(int i=0;i<t;i++)
{
scanf("%f",&a[i]);
}
int res=search(a,t);
printf("%.3f %d",a[res],res);
return 0;
}
sort代碼:
#include<cstdio>
#include<algorithm>
using namespace std;
struct Node{
int x;
float y;
}a[1005];
bool cmp(Node q,Node w)
{
return q.y>w.y;
}
int main()
{
int t;
scanf("%d",&t);
for(int i=0;i<t;i++)
{
scanf("%f",&a[i].y);
a[i].x=i;
}
sort(a,a+t,cmp);
printf("%.3f %d",a[0].y,a[0].x);
return 0;
}