[英]How to find largest and smallest number in c
I have found the solution in particular size of array. 我找到了特定大小的数组的解决方案。 However, how can I get the largest and smallest numbers without asking to input the size of the array?
但是,如何在不要求输入数组大小的情况下获得最大和最小的数字? thanks
谢谢
eg It will only return 65 and -1 when I input numbers like 1, 0, -1, 5, 43, 65. I want to ignore the step for entering the size of the array which is 6 for this case. 例如,当我输入1、0,-1、5、43、65之类的数字时,它只会返回65和-1。在这种情况下,我想忽略输入数组大小为6的步骤。
#include<stdio.h>
int main(){
int a[50],size,i,big,small;
printf("\nEnter the size of the array: ");
scanf("%d",&size);
printf("\nEnter %d elements in to the array: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
big=a[0];
for(i=1;i<size;i++){
if(big<a[i])
big=a[i];
}
printf("Largest element: %d",big);
small=a[0];
for(i=1;i<size;i++){
if(small>a[i])
small=a[i];
}
printf("Smallest element: %d",small);
return 0;
}
I'll go you one further. 我再去找你 You don't need an array for this in the first place, thereby making the size-input-avoidance trivial (there is no need for it, because there is no array):
首先,您不需要数组,从而避免了大小输入避免问题(因为没有数组,因此不需要它):
#include <stdio.h>
int main()
{
int val;
printf("Enter number: ");
fflush(stdout);
if (scanf("%d", &val) == 1)
{
int big = val, small = val;
do
{
if (big < val)
big = val;
if (val < small)
small = val;
printf("Enter number: ");
fflush(stdout);
} while (scanf("%d", &val) == 1);
printf("Largest element: %d\n",big);
printf("Smallest element: %d\n",small);
}
return 0;
}
could define a macro which lets you calculate the number of entries in an array 可以定义一个宏,让您计算数组中的条目数
#define ArrayLength(arr) (sizeof(arr)/sizeof(arr[0]))
...
int x;
for(x=0;x<ArraLength(myArray);x++){...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.