歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用C語言求一組數組的最大值以及最小值

用C語言求一組數組的最大值以及最小值

日期:2017/3/1 10:03:54   编辑:Linux編程

用C語言求一組數組的最大值以及最小值

#include<stdio.h>//stdio.h是c的標准的i/o庫,是以函數的方式向buffer寫入或讀取字符,iostream.h是c++的標准i/o庫,引入了輸入/輸出流的概念,是一個類庫,是以類方法從streambuf中讀取,寫入字符。
int max=0;
int min=1000;
void change(int a[],int n)
{
int i,j,k;
for(i=1;i<n;i++)
if(a[i]<min)
{
min=a[i];
j=i;
}
for(i=1;i<n;i++)
if(a[i]>max)
{
max=a[i];
k=i;
}
a[k]=min;
a[j]=max;
printf("the position of min is:%3d\n",j);
printf("the position of max is:%3d\n",k);
printf("Now the array is:\n");
for(i=0;i<n;i++)
printf("%5d",a[i]);
}
main()
{
int a[20],i,n;
printf("please input the number of elements:\n");
scanf("%d",&n);
printf("please imput the elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
change(a,n);
printf("\nmax=%d\nmin=%d\n",max,min);
}

www.linuxidc.com @linux:~/c編程$ gcc example.c -o example
www.linuxidc.com @linux:~/c編程$ ./example
please input the number of elements:
3
please imput the elements:
1
3
5
the position of min is: 0
the position of max is: 2
Now the array is:
5 3 1
max=5
min=1

Copyright © Linux教程網 All Rights Reserved