A Tasty Morsel

Given this requirement:

The conversion rate you should use is 6.75 CNY for every 1 USD. All numbers should be represented as a string with 2 decimal places. (e.g. "21.00" NOT "21.0" or "21")

Why does this code:

char *USD_to_CNY (long dollars, char *yuans)

{

  sprintf(yuans, "%.2f Chinese Yuan", 6.75*dollars); // write to yuans

  return yuans; // return it

}

Given this problem:

for 122978293824730344 dollars, expected "830103483316929822.00 Chinese Yuan", but got "830103483316929792.00 Chinese Yuan"

The answer : the input uses 54 bits, and your type has insufficient precision. So, use long long with 675 instead of 6.75, and do a divide by 10 at the sprintf.

The title - from a book in which I read this joke: "What do a passionate kiss and a spider have in common? Both lead to the undoing of the fly."

Comments

Popular posts from this blog

Poor Documentation - How Could You Do this to Us K&R?

A Classic C Programming Mistake - See if You Can Spot it