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

前端 未结 9 1226
無奈伤痛
無奈伤痛 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条回答
  •  梦毁少年i
    2021-01-30 02:42

    This reminds me of an assignment that I failed

    Way back in the 90's. The lecturer had been sprouting on about loops and, long story short, our assignment was to write a function that would return the number of digits for any given integer > 0.

    So, for example, the number of digits in 321 would be 3.

    Although the assignment simply said to write a function that returned the number of digits, the expectation was that we would use a loop that divides by 10 until... you get it, as covered by the lecture.

    But using loops was not explicitly stated so I: took the log, stripped away the decimals, added 1 and was subsequently lambasted in front of the whole class.

    Point is, the purpose of the assignment was to test our understanding of what we had learned during lectures. From the lecture I received I learned the computer teacher was a bit of a jerk (but perhaps a jerk with a plan?)


    In your situation:

    write a function in C/C++ that returns the sum of the digits of the number squared

    I would definitely have provided two answers:

    • the correct answer (squaring the number first), and
    • the incorrect answer in keeping with the example, just to keep him happy ;-)

提交回复
热议问题