簡體   English   中英

如何找到不帶數組的C中最大整數的出現?

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

在我的代碼中,我能夠找到一組要求輸入的數字中的最大整數。 我找不到我輸入的最大整數的出現次數。 我覺得我的問題出在“ if and else”語句上。 例如,當滿足第一個if語句時,我認為它會使“ count”增加一次,並跳過所有其他“ if and else”語句,並執行最后一個打印功能。 因此,計數總是以2結尾。

如何使count計數最大整數的出現次數?

#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;

}

我認為您太過復雜了。 您可能只有一個變量,而不是五個變量,然后循環輸入該變量,並隨手保存最大值和計數:

#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);

如果您不需要5個變量,那么Mureinik會給出答案。 如果您必須擁有5個這樣的變量:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM