編寫一個 C 程式找出系列中的最大和最小數字


問題

讓使用者在控制檯輸入四個整數系列,找出系列中最小和最大的數字

要計算最小和最大數字,我們使用 if 條件。我們用來找出最大和最小數字的邏輯為 -

if(minno>q) //checking 1st and 2nd number
   minno=q;
else if(maxno&l;q)
   maxno=q;
if(minno>r) //checking 1st and 3rd number
   minno=r;

程式 1

 即時演示

#include<stdio.h>
int main(){
   int minno,maxno,p,q,r,s;
   printf("enter any four numbers:");
   scanf("%d%d%d%d",&p,&q,&r,&s);
   minno=p;
   maxno=p;
   if(minno>q) //checking 1st and 2nd number
      minno=q;
   else if(maxno<q)
      maxno=q;
   if(minno>r) //checking 1st and 3rd number
      minno=r;
   else if(maxno<r)
      maxno=r;
   if(minno>s) //checking 1st and 4th number
      minno=s;
   else if(maxno<s)
      maxno=s;
   printf("Largest number from the given 4 numbers is:%d
",maxno);    printf("Smallest numbers from the given 4 numbers is:%d",minno);    return 0; }

輸出

enter any four numbers:34 78 23 12
Largest number from the given 4 numbers is:78
Smallest numbers from the given 4 numbers is:12

程式 2

以下程式查詢陣列中的最小和最大元素 -

#include<stdio.h>
int main(){
   int a[50],i,num,large,small;
   printf("Enter the number of elements :");
   scanf("%d",&num);
   printf("Input the array elements :
");    for(i=0;i<num;++i)       scanf("%d",&a[i]);    large=small=a[0];    for(i=1;i<num;++i){       if(a[i]>large)          large=a[i];       if(a[i]<small)          small=a[i];    }    printf("small= %d
",small);    printf("large= %d
",large);    return 0; }

輸出

Enter the number of elements :8
Input the array elements :
1
2
6
4
8
9
3
9
small= 1
large= 9

更新日期:05-3-2021

16K+ 瀏覽量

開啟您的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.