Home > Net >  Find and print three-digit positive integers which the value of the first digit is the sum of 2nd an
Find and print three-digit positive integers which the value of the first digit is the sum of 2nd an

Time:11-14

I've tried to separate the last digit and the second one and then add them up to compare with the first. How many loops should I use and how to apply?

I've tried to separate the last digit and the second one and then add them up to compare with the first one.But I don't know how to.

#include <iostream>
using namespace std;
int main()
{
    unsigned int x, counter = 0 ,s = 0, j = 1;
    for (int i = 100; i <= 999; i  )
    {
        x = i;
        s = s   (x % 10);
        x = x / 10;
        s = s   (x % 10);
        x = x / 10;
        if (x / 10 == 0)
            break;
        cout << x;
    }
    
}

CodePudding user response:

I can see some mistakes in the posted attempt.

  • The variable s, which should represent the sum of the second and third digits, is declared and initialized outside the loop, but its value should be reset to 0 at the beginning of the loop, otherwise it accumulates the value of all those digits in all the three digits numbers tested.

  • the if (x / 10 == 0) break line terminates the loop at its first iteration. It should neither divide x, as it's already the "first" digit, nor test it against 0 (why have you calculated the sum, if you are not using it?), nor break the loop.

  • The line cout << x; is, well, unreachable (because of the previous test) and wrong, as it prints (or at least tries to) the "first" digit, while the assignment requires to print the three digits numbers that satisfy the rules. So you should (conditionally, when i == s) print i instead.

  • Related