Machine-translated by Google. Questions are authored in English.
Top

Discussion

The library function sqrt operates on a double precision argument. If, i is an integer variable, then which of the following calls would correctly compute sqrt(i)?

  • A.sqrt((double)i)
  • B.(double)sqrt(i)?
  • C.(double)(sqrt(i))
  • D.sqrt(i)

Answer: A

Correct answer: sqrt((double)i)

The cast must be applied to the argument, before the call, so that the value passed has the type the function expects.

In practice a prototype from math.h would convert i automatically, so sqrt(i) also works when the header is included - but the explicit cast is correct regardless and states the intent. Casting the result, as the other options do, is too late: it converts a value the function has already computed, and without a prototype the argument would have been passed as an int and misinterpreted.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.