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

前端 未结 9 1212
無奈伤痛
無奈伤痛 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:32

    As others have pointed out, the special treatment for n==0 is nonsense, since for every serious C programmer it is obvious that "while(n)" does the job.

    The behaviour for n<0 is not that obvious, that's why I would prefer to see those 2 lines of code:

    if (n < 0) 
        n = -n;
    

    or at least a comment:

    // don't worry, works for n < 0 as well
    

    Honestly, at what time did you start considering that n might be negative? When writing the code or when reading your teacher's remarks?

提交回复
热议问题