Home Ask Login Register

Developers Planet

Your answer is one click away!

Will Njundong January 2017

Why does my If-Else Keep never evaluate to true?

I'm supposed to count the number of times variable integer "num" divided by each of its digit results in a clean quotient (has a remainder of 0).

Note: Each digit is considered to be unique, so each occurrence of the same evenly divisible digit should be counted (i.e.: for 222, the answer is 3).

int solver(int num) //gets an integer
    string numString = to_string(num); //convert integer to string so i can manipulate individual digits
    int divisible=0; //will store a count of digits in "num" which can be divided evenly

    for (int x = 1; x <= (end(numString) - begin(numString))/*string length*/; x++)

        if (numString[x-1] == 0 || (end(numString) - begin(numString))-x >=1) //ignore digits which are 0 and or 0s that are last in the array

        if (num % numString[x - 1] == 0) //THIS NEVER EVALUATES TO TRUE. HOW COME???

    return divisible;  //number of digits in variable "num" which can be evenly divided

This function ALWAYS returns 0 (that's what variable int "divisible was initialized to), because the if-else for incrementing it always evaluates to false and is skipped. I have checked and made sure the If-Else arguments hold valid numbers (they're all integers). Is it because they are all integers that the decimal part of the result never reach If-Else for evaluation? That's the best possibility I can come up with, and even then I don't know how to remedy.


Manos Nikolaidis January 2017

  1. learn about size() function of std::string. You don't need end and begin to get the length of a string.
  2. numString[x-1] returns a char an ASCII code, not the digit as numeric value. The ASCII code of 0 in decimal for example is 48. To get the numeric value of a single digit you could do: numString[x-1] - '0'

Post Status

Asked in January 2017
Viewed 2,021 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life