简体   繁体   中英

How to find occurrences of the largest integer in C without array?

In my code, I was able to find the largest integer within a set of numbers that ask to be inputted. I was not able to find the number of occurrences my largest integer was inputted. I feel like my problem is with the "if and else" statements. For example, when the first if statement is satisfied, I think it increments the "count" once and skips over all the other "if and else" statements and executes the last print function. So the count always ends up as 2 .

What can I do to have the count count the number of occurrences of the largest integer?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

int main ()
{
    int count;
    int a,b,c,d,e;
    count = 1;

printf("Enter 5 integers within 1-10:\n");
scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);


if (e >= a 
 && e >= b 
 && e >= c 
 && e >= d){
    printf ("Largest integer is %d\n", e);
    count++;
    }

else if (d >= a 
      && d >= b 
      && d >= c 
      && d >= e){
    printf ("Largest integer is %d\n", d);
    count++;

    }

else if (c >= a 
      && c >= b 
      && c >= d 
      && c >= e){
    printf ("Largest integer is %d\n", c);
    count++;
    }

else if (b >= a 
      && b >= c 
      && b >= d 
      && b >= e){
    printf ("Largest integer is %d\n", b);
    count++;
    }

else {
    printf ("Largest is %d\n", a);
    count++;
    }       

printf ("Largest integer occurred %d times.\n", count);
system ("pause");
return 0;

}

I think you're over-complicating things. Instead of five variables, you could have just one, and input to it in a loop, saving the maximum and the count as you go:

#define NUMBER_OF_VARS 5

int i;
int input;
int curr_max = INT_MIN;
int count = 0;

for (i = 0; i < NUMBER_OF_VARS; ++i) {
    printf("Enter an integer: ");
    scanf("%d", &input);

    if (input > curr_max) {
        curr_max = input;
        count = 1;
    } else if (input == curr_max) {
        ++count;
    }
}

printf ("Largest integer is %d, appearing %d times\n", curr_max, count);

If you don't need 5 vars, then Mureinik has the answer. If you you have to have the 5 variables that I'd do it like this:

int max = -9999;
if (a > max) {
    max = a;
}
if (b > max) {
   max = b;
}
/* repeat for c d and e */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM