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

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

    Summarizing a discussion that's been percolating in the comments:

    • There is no good reason to test in advance for n == 0. The while(n) test will handle that case perfectly.
    • It's likely your teacher is still used to earlier times, when the result of % with negative operands was differently defined. On some old systems (including, notably, early Unix on a PDP-11, where Dennis Ritchie originally developed C), the result of a % b was always in the range [0 .. b-1], meaning that -123 % 10 was 7. On such a system, the test in advance for n < 0 would be necessary.

    But the second bullet applies only to earlier times. In the current versions of both the C and C++ standards, integer division is defined to truncate towards 0, so it turns out that n % 10 is guaranteed to give you the (possibly negative) last digit of n even when n is negative.

    So the answer to the question "What is the meaning of while(n)?" is "Exactly the same as while(n != 0)", and the answer to "Will this code work properly for negative as well as positive n?" is "Yes, under any modern, Standards-conforming compiler." The answer to the question "Then why did the instructor mark it down?" is probably that they're not aware of a significant language redefinition that happened to C in 1999 and to C++ in 2010 or so.

提交回复
热议问题