问题
How to search for the biggest number, in a set of integers (cat1, cat2, cat3, cat4) I code this, contemplating every alternative, except for the == alternatives (longer code!!) Is there a more efficient, or simpler way to do it, than making an IF satement for every possible solution? If the number of numbers is bigger? (e.g. 10!!!!) Thanks. This is my code
if (cat1 > cat2 && cat1> cat3 && cat1>cat4)
printf("cat 1 is the biggest", cat1);
if (cat2 > cat1 && cat2> cat3 && cat2>cat4)
printf("cat 2 is the biggest", cat2) ;
if (cat3 > cat1 && cat3> cat2 && cat3>cat4)
printf("cat 3 is the biggest", cat3) ;
if (cat4 > cat1 && cat4> cat2 && cat4>cat3)
printf("cat 4 is the biggest", cat4);
回答1:
Pretty straightforward with an array:
int data[10] = // ... your ints;
int max = data[0];
for (int i = 1 ; i < 10 ; i++ )
if (data[i] > max ) max = data[i];
回答2:
this function accepts an array and its size as input.
int biggest(int *nn,int n) {
int rv = *nn;
for(++nn,--n;n;--n,++nn) if(rv<*nn) rv = *nn;
return rv;
}
回答3:
Just use an array. Here is an example of finding the biggest number of an array of any size.
int main(){
int size,i,biggest;
int *a = NULL;
printf("\nEnter the size of the array: ");
scanf("%d",&size);
a = malloc(size * sizeof(int));
printf("\nEnter %d elements in to the array: ”, size);
for(i=0; i<size; i++)
scanf("%d",&a[i]);
// assume the first number is the biggest
biggest=a[0];
// iterate on the array and update the biggest number if the current value is bigger than 'biggest'
for(i=1; i<size; i++){
if( biggest < a[i])
biggest=a[i];
}
printf("\nYour biggest number is: %d",biggest);
free(a)
return 0;
}
回答4:
int MAX(int a, int b) {
return a > b ? a : b;
}
// later on...
return MAX(cat1, MAX(cat2, MAX(cat3, cat4)));
来源:https://stackoverflow.com/questions/12788713/searching-for-the-biggest-integer-in-c-more-than-2