开发者

Exercise from C book

I wanted to know if the following two statements are equivalent, and if not, why not. Thanks.

1)

if (score >= 90)
  printf("A");
else if (score >= 80)
  printf("B");
else if (score >= 70)
  printf("C");
else if (score >= 60)
  printf("D");
else
  printF("F");

2) Ver开发者_如何转开发sion 1

if (score < 60)
  printf("F");
else if (score > 70)
  printf("D");
else if (score > 80)
  printf("C");
else if (score > 90)
  printf("B");
else
  printf("A");


2) Version 2

if (score < 60)
  printf("F");
else if (score < 70)
  printf("D");
else if (score < 80)
  printf("C");
else if (score < 90)
  printf("B");
else
  printf("A");

I'm sorry, I mispelled the sign in the second option. Are they equivalent now?


They are not equivelent.

For example, say you have a "score" of 95 - in the first option, you'll print "A", but in the second, you'll print "D"...

Now, I suspect that there is a typo in the above. If you switch all of the comparisons in the second example to < instead of >, then they will both print the same answer.

However, they would still not be equivalent, (at least prior to compiler optimization). There are some subtle differences. For example, the second will return faster for "D" than the first, but the first would return faster for "B". Granted, this is a very subtle difference, but they are different.


Edit: The suspicion of a typo above was true based on the edit. See the second half for differences which still remain.

These will print the same value, but they are not equivalent.


No, plug in a value of 99 and see what happens in both cases.

For the first, you'll see A, for the second, D.

Now, if all those > were < in the second piece of code, that may be a different story (nudge, nudge, wink, wink, a nod's as good as a wink to a blind bat, say no more).


Now, based on your edit, (changing the > to < as suggested), they are equivalent. In terms of output, anyway. There are a great many other things that may still be different such as performance in the case where everyone fails :-)

But, I'm assuming the output is what you were interested in.


They are not. Reverse the comparison in the second set of 70, 80, and 90 tests.


No. If score is, say, 95, then the second example will print "D" while the first will print "A".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜