【发布时间】:2021-03-20 19:59:02
【问题描述】:
我采用了一段较大的代码来强调。该代码工作正常(良好的输出),但我有一个问题。在下面的代码中,为什么会出现两个“else if”语句正在执行?我了解到拥有一系列“if”语句与“else if”之间的区别在于所有“if”语句都被执行,但是当使用一系列“else if”语句时,当一个语句被执行时,程序不会在该线程上继续。看来输入 1 1 2 2 会执行下面的两个代码,但它不会只执行第一个“else if”语句吗?如果是这样,为什么会有 ixlarge = 4 的输出?
else if (x3 >= x4 && x3 >= x2 && x3 >= x1)
xlarge = x3;
else if(x4 >= x3 && x4 >= x2 && x4 >= x1)
xlarge = x4;
#include <stdio.h>
int main( )
{
int x1, x2, x3, x4;
int xlarge, xsmall, ixlarge, ixsmall;
while( 1 )
{
printf( "enter x1, x2, x3, x4:\n" );
scanf( "%d%d%d%d", &x1, &x2, &x3, &x4 );
xlarge = -1;
xsmall = -1;
if(x1 >= x2 && x1 >= x3 && x1 >= x4 )
xlarge = x1;
else if((x2 >= x3 && x2 >= x4 && x2 >= x1))
xlarge = x2;
else if (x3 >= x4 && x3 >= x2 && x3 >= x1)
xlarge = x3;
else if(x4 >= x3 && x4 >= x2 && x4 >= x1)
xlarge = x4;
printf("%d",xlarge);
if(x1 == xlarge)
ixlarge = 1;
if(x2 == xlarge)
ixlarge = 2;
if(x3 == xlarge)
ixlarge = 3;
if(x4 == xlarge)
ixlarge = 4;
printf("%d",ixlarge);
/*if(x3 == xlarge && x4 == xlarge)
ixlarge = 4;*/
if(x1 <= x2 && x1 <= x3 && x1 <= x4 )
xsmall = x1;
else if((x2 <= x3 && x2 <= x4 && x2 <= x1))
xsmall = x2;
else if (x3 <= x4 && x3 <= x2 && x3 <= x1)
xsmall = x3;
else if(x4 <= x3 && x4 <= x2 && x4 <= x1)
xsmall = x4;
if(x1 == xsmall)
ixsmall = 1;
if(x2 == xsmall)
ixsmall = 2;
if(x3 == xsmall)
ixsmall = 3;
if(x4 == xsmall)
ixsmall = 4;
if(x3 == xsmall && x4 == xsmall)
ixsmall = 3;
if(x2 == xsmall && x1 == xsmall)
ixsmall = 1;
if(x1 == xsmall && x3 == xsmall)
ixsmall = 1;
if(x1 == xsmall && x4 == xsmall)
ixsmall = 1;
if(x2 == xsmall && x3 == xsmall)
ixsmall = 2;
if(x2 == xsmall && x4 == xsmall)
ixsmall = 2;
if(x1 == xsmall && x3 == xsmall && x2 == xsmall)
ixsmall = 1;
if(x1 == xsmall && x4 == xsmall && x2 == xsmall)
ixsmall = 1;
printf( "largest = %4d at position %d, ", xlarge, ixlarge );
printf( "smallest = %4d at position %d\n", xsmall, ixsmall );
}
return 0;
}
【问题讨论】:
-
您是否尝试过使用调试器逐语句逐句执行代码,看看真正会发生什么?
-
您正在查看错误的代码部分。您突出显示的内容将设置
xlarge = x3,即xlarge = 2。但是您的问题是关于如何设置ixlarge。查看以if(x1 == xlarge)开头的代码部分,注意那里有noelse块。另请注意,由于x3和x4具有相同的值,所以表达式x3 == xlarge和x4 == xlarge都是正确的。 -
不是
else if。是if语句将ixlarge设置为 3,然后设置为 4。为了便于调试,在每个if、else if和else中放置一个printf以查看程序流程。跨度> -
顺便说一句,我希望这段冗长乏味的代码能成为学习循环的良好动力。
-
我重申我关于使用调试器的观点...如果您使用调试器单步执行代码,您可能会在比编写问题更短的时间内发现问题本身。能够调试自己的代码是任何程序员的关键和强制性知识。