首页 > 试题广场 >

下面程序中的关系表达式过于复杂,并有些错误,请简化并改正它。

[问答题]
下面程序中的关系表达式过于复杂,并有些错误,请简化并改正它。
#include <stdio.h>
int main (void)                                                                                      /* 1 */
{                                                                                                           /* 2 */
int weight, height; /* weight 以磅为单位, height 以英寸为单位 */
/* 4 */
scanf ("%d, weight, height);                                                        /* 5 */
if (weight < 100 && height>64)                                                   /* 6 */
if (height >= 72)                                                                   /* 7 */
printf ("You are very tall for your weight.\n");
else if (height < 72 &&  > 64)                                              /* 9 */
printf ("You are tall for your weight.\n");                     /* 10 */
else if (weight > 300 && ! (weight <= 300))                              /* 11 */
&&height<48)                                                               /* 12 */
if (! (height >= 48)                                                             /* 13 */
printf (" You are quite short for your weight.\n");
else                                                                                          /* 15 */
printf (" Your weight is idea.\n");                                       /* 16 */
/* 17 */
return 0;
}

推荐
第5行:应该是scanf ("%d%d", &weight, &height);。在scanf()中不要忘记使用&运算符。这一行前面也应该有提示输入的语句。但第6行已经保证height>64,因此,不需要任何测试,并且if else应该是else。
第9行:它的意思是(heiget<72&&height>64)。但是表达式的第一部分是不必要的,因为既然程序已经到达了这个else if,那么height必然小于72.因此一个简单的(height>64)就可以了。
第11行:条件冗余;第二个子表达式(weight不是小于或等于300的)与第一个子表达式意义相同。所需要的只是一个简单的(weight>300)。但是这里还有更多的问题。第11行属于一个不正确的if!很明显,这个else是与第6行中的if相匹配的。但是根据if的“最接近规则”,它会与第9行的if相匹配。因此会在weight小于100并且height小于或等于64时到达第11行。这就使得在到达该语句时weight不可能超过300。
第7到9行:应该用花括号括起来。这样第11行就会是第6行而不是第9行的可选情况。而如果第9行的else if由一个简单的else替代了,就不再需要花括号了。
第13行:应该简化为if(height>48)。其实这一行完全可以忽略,因为第12行已经作了这种测试。
第15行:这个else与第13行的if相匹配。把第13和14行括在花括号中可以强制使这个else与第11行的if相匹配。或者,按照建议,简单地删掉第13行。
下面是一个正确的版本:
#include <stdio.h>
int main (void)
{
int weight, height; /* weight 以磅为单位, height 以英寸为单位 */
printf ("Enter your weight in pounds and ");
printf ("your height in inches.\n");
scanf ("%d %d, &weight, &height);
if (weight < 100 && height>64)
if (height >= 72)
printf ("You are very tall for your weight.\n");
else
printf ("You are tall for your weight.\n");
else if (weight > 300 && height < 48)
printf (" You are quite short for your weight.\n");
else
printf (" Your weight is idea.\n");
return 0;
}

发表于 2018-03-23 22:23:53 回复(0)