开发者

Need help with C++ Loops Exercise

From Cay Horstmann's "C++ For Everyone" Chapt开发者_StackOverflow社区er 4: Loops

Write a program that adds up the sum of all odd digits of n. (For example, if n is 32677, the sum would be 3 + 7 + 7 = 17)

I don't know how to make the computer "see" the numbers like separate them


n % 10 gets the value of the one's digit. You can figure it out from there right?


Here's a hint. C++ has the modulus operator %. It will produce the remainder when two numbers are divided together. So if I wanted to know the last digit in a number which was greater than 10 I would modulus 10 and get the result

int lastDigit = number % 10;


The last digit of a base-10 integer i is equal to i % 10. (For reference, % is the modulus operator; it basically returns the remainder from dividing the left number by the right.)

So, now you have the last digit. Once you do, add it to a running total you're keeping, divide i by 10 (effectively shifting the digits down by one place), or in your case 100 (two places), and start back at the beginning. Repeat until i == 0.


People here rather not provide you with the answer to your exercise, but to provide you with hints so that you can find the answer on your own and more importantly understand it.

To start, the following arithmetic operations will help you:

loop:
  right_most_digit = n % 10
  n = n / 10
end_loop
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜