1
#include <iostream>
#include <string>

using namespace std;

int main() {
    int n = 12;
    int i, res;
    string digits = to_string(n);


    for(i = 0; i < digits.length(); i++){
        res = 0;
        res = n % digits[i];

    if (res != 0){
        res = false;
        break;
    }

    if (res == 0){
        res = true;
    }
}

The digits[0] is 1, therefore: 12 % 1 = 0 = res. However, when I run the program, res = 12, so the following if conditions do not work correctly. What's wrong?

Thanks

5
  • 2
    The if conditions are not in the loop, so they're just using res from the last digit. Commented Feb 22, 2020 at 18:17
  • 1
    digits[0] is 49, not 1. Commented Feb 22, 2020 at 18:19
  • I have changed it but is is still the same Commented Feb 22, 2020 at 18:19
  • I don´t understand why digits[0] = 49 Commented Feb 22, 2020 at 18:20
  • Because when you use a char as a number, you get the character code. Commented Feb 22, 2020 at 18:21

1 Answer 1

1
digits[0]

Contains the character '1', which has a numeric value of 49. You are evaluating 12 % 49 which is indeed 12.

If you want to convert a numeric character to its value, you can do it like (digits[i] - '0').

Change

res = n % digits[i];

to

res = n % (digits[i] - '0');

But only if you're certain that digits will only contain characters that are digits.

The ASCII character codes can be found by googling for them. This page seems fine.

https://www.asciitable.xyz/

Sign up to request clarification or add additional context in comments.

4 Comments

Since she created digits by converting a number to a string, the last condition is guaranteed.
@Barmar agreed but thought it was worth including for the next iteration of the program where they take user input.
Hopefully that input would be done to the int variable, not directly to the string.
@Barmar "hopefully"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.