我取了一段更大的代码来强调。代码工作正常(很好的输出),但我有一个问题。在下面的代码中,为什么会出现两个“如果”语句被执行呢?我了解到,拥有一系列'if‘语句与'else if’语句之间的区别在于,所有'if‘语句都被执行,但是当使用一系列'else if’语句时,当一个语句被执行时,程序就不会在该线程上继续运行。输入1,12,2,2执行下面的两个代码,但是它不是只执行第一个'else‘如果’语句‘吗?如果是这样的话,那么为什么会有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;
}发布于 2021-03-20 20:06:51
在输入为"1 1 2 2“的情况下,x3和x4的值都为2,因此这个块:
else if (x3 >= x4 && x3 >= x2 && x3 >= x1)
xlarge = x3;是被执行的,尽管如果执行了另一个,xlarge仍然具有相同的值。表示x4最大的部分如下:
if(x3 == xlarge)
ixlarge = 3;
if(x4 == xlarge)
ixlarge = 4;因为x3和x4具有相同的值,所以这两个if块都将执行,使得ixlarge的值为4。
您可以通过更改这组if语句来解决这个问题:
if(x1 == xlarge)
ixlarge = 1;
if(x2 == xlarge)
ixlarge = 2;
if(x3 == xlarge)
ixlarge = 3;
if(x4 == xlarge)
ixlarge = 4;转至if/else
if(x1 == xlarge)
ixlarge = 1;
else if(x2 == xlarge)
ixlarge = 2;
else if(x3 == xlarge)
ixlarge = 3;
else if(x4 == xlarge)
ixlarge = 4;并在设置ixsmall时执行类似的更改。
在一个边节点上,如果您使用数组和循环而不是4个单独的变量,您的代码可以使更简单、更容易出错。
https://stackoverflow.com/questions/66725915
复制相似问题