Do I need to explicitly handle negative numbers or zero when summing squared digits?

前端 未结 9 1221
無奈伤痛
無奈伤痛 2021-01-30 01:51

I recently had a test in my class. One of the problems was the following:

Given a number n, write a function in C/C++ that returns the su

9条回答
  •  醉酒成梦
    2021-01-30 02:39

    I don't completely like either your version or your teacher's. Your teacher's version does the extra tests that you correctly point out are unnecessary. C's mod operator is not a proper mathematical mod: a negative number mod 10 will produce a negative result (proper mathematical modulus is always non-negative). But since you're squaring it anyway, no difference.

    But this is far from obvious, so I would add to your code not the checks of your teacher, but a big comment that explains why it works. E.g.:

    /* NOTE: This works for negative values, because the modulus gets squared */

提交回复
热议问题