sonlas10
sonlas10

Reputation: 175

Why modulus operator does not work on that code?

#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

Upvotes: 1

Views: 69

Answers (1)

JohnFilleau
JohnFilleau

Reputation: 4288

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/

Upvotes: 1

Related Questions