1159 最大的兩個數(指針專題)


題目來源:
https://acm.zzuli.edu.cn/zzuliacm/problem.php?id=1159
Description

求n個整數中的最大的兩個元素。要求定義一個函數LargestTow(),求數組a的最大的兩個元素,分別存入形參指針pfirst和psecond所指存儲單元,函數原型如下:
void LargestTow(int a[],int n,int *pfirst,int *psecond)
{
/*數組a有n個元素,將數組中的最大值存入形參指針pfirst所指內存單元,將數組中第二大的值存入形參指針psecond所指內存單元。 */
}

Input
輸入有兩行,輸入第一行是一個整數n,1<n<=1000;第二行是n個整數,由空格隔開。
Output
輸出兩個整數,表示數組中最大的兩個值。輸出占一行。
Sample Input
5
6 3 4 9 8
Sample Output
9 8
題意描述:
輸入元素的個數n以及n個整數
調用LargestTow()函數計算並輸出該數組中最大和第二大的兩個數
解題思路:
調用sort函數,將指針賦值即可
程序代碼:

 1 #include<stdio.h>
 2 void LargestTow(int a[],int n,int *pfirst,int *psecond);
 3 #include<algorithm>
 4 using namespace std;
 5 int main()
 6 {
 7     int n,a[1010],i;
 8     int pfirst,psecond;
 9     scanf("%d",&n);
10     for(i=0;i<n;i++)
11         scanf("%d",&a[i]);
12     LargestTow(a,n,&pfirst,&psecond);
13     printf("%d %d\n",pfirst,psecond);
14     return 0;
15 }
16 void LargestTow(int a[],int n,int *pfirst,int *psecond)
17 {
18     sort(a,a+n);
19     *pfirst=a[n-1];
20     *psecond=a[n-2];
21 }

 


易錯分析:
指針作為函數參數的用法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM