[英]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.