简体   繁体   中英

Need help with C++ Loops Exercise

From Cay Horstmann's "C++ For Everyone" Chapter 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM