我是C编程的新手,我最近碰到了从3个数字中找到第2大数字的问题。我尝试使用if ... else,但总是给出最小的数字作为输出。我在这段代码中犯的逻辑错误是什么?
#include<stdio.h>
int main() {
int a;
int b;
int c;
a=10;
b=30;
c=7;
if(a>b) {
if(a>c) {
if(b>c)
printf("2nd largest is %d",c);
else
printf("2nd largest is %d",b);
}
} else
{
if(b>c) {
if(c>a)
printf("2nd largest is %d",a);
else
printf("2nd largest is %d",c);
} else
printf("2nd largest is %d",b);
}
}
答案 0 :(得分:2)
if(a>b) {
if(a>c) { //a is the greatest!
if(b>c) // the *greater* of the two remaining is the second greatest
printf("2nd largest is %d",c); // if b > c, output b!
else
printf("2nd largest is %d",b); // if c > b, output c!
} // I think this got missed: What if c > a and a > b?
} else
{
if(b>c) { //b is the greatest!
if(c>a) //As above, the *greater* of the two remaining is what you are looking for
printf("2nd largest is %d",a); // c is greater, so output it
else
printf("2nd largest is %d",c); // a is greater
} else // c > b and b > a, this is correct.
printf("2nd largest is %d",b);
}
答案 1 :(得分:1)
逻辑很好,但需要交换变量的打印,如下所示
1)
if(b>c)
printf("2nd largest is %d",b);
else
printf("2nd largest is %d",c);
2)
if(c>a)
printf("2nd largest is %d",c);
else
printf("2nd largest is %d",a);
答案 2 :(得分:1)
if(a>=b && a>=c) {
if(b>=c) printf("2nd largest is %d",b);
else printf("2nd largest is %d",c);
} else if(b>=a && b>=c) {
if(a>c=) printf("2nd largest is %d",a);
else printf("2nd largest is %d",c);
} else if(c>=a && c>=b) {
if(a>=b) printf("2nd largest is %d",a);
else printf("2nd largest is %d",b);
}
或
static int middleVal(int a, int b, int c) {
if(a >= b && a >= c) return b > c? b : c;
return middleVal(b,c,a);
}
答案 3 :(得分:0)
有很多方法可以执行这些操作,但是如果您只使用了二进制最小和最大功能:
printf("2nd largest is %d", min(min(max(a,b),max(b,c)),max(a,c)));
如果您需要更通用的选择(不仅是第二大元素,而是第k个最大元素),请使用像quickselect这样的选择算法:http://en.wikipedia.org/wiki/Quickselect#Algorithm
答案 4 :(得分:0)
我建议你使用qsort和数组来实现这个有一个例子:
#include <stdio.h>
#include <stdlib.h>
// This is a custom function for qsort where we define the sort rules
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)b - *(int*)a );
}
int main() {
int n;
// Set the number of element
int values[] = {10, 30, 7};
// Dynamically get the number of element
int nbOfValue;
nbOfValue = sizeof(values) / sizeof(int);
// Set the number of element to display
int nbOfValueToDisplay = 2;
/*
Will reorganize you array value
*/
qsort(values, nbOfValue, sizeof(int), cmpfunc);
for (n = 0 ; n < nbOfValueToDisplay; n++ ) {
printf("%d ", values[n]);
}
}