编写一个 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;
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
程序 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
广告