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

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

    Generally in assignments not all the marks are given just because the code works. You also get marks for making a solution easy to read, efficient and elegant. These things are not always mutually exclusive.

    One I can't strees enough is "use meaningful variable names".

    In your example it does not make much difference, but if you're working on a project with a milion lines of code readability becomes very important.

    Another thing I tend to see with C code is people trying to look clever. Rather than using while(n != 0) I'll show everyone how clever I am by writing while(n) because it means the same thing. Well it does in the compiler you have but as you suggested you teacher's older version has not implemented it the same way.

    A common example is referencing an index in an array while incrementing it at the same time ; Numbers[i++] = iPrime;

    Now, the next programmer who works on the code has to know if i gets incremented before or after the assignment, just so someone could show off.

    A megabyte of disk space is cheaper that a roll of toilet paper, go for clarity rather than trying to save space, your fellow programmers will be happier.

提交回复
热议问题