gpt4 book ai didi

c - 3 个数字中的第二大,使用 if_else

转载 作者:太空狗 更新时间:2023-10-29 15:04:07 26 4
gpt4 key购买 nike

我是 C 编程的新手,最近遇到了从 3 个数中找出第二大数的问题。我尝试使用 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);
}
}

最佳答案

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

关于c - 3 个数字中的第二大,使用 if_else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22335047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com