簡體   English   中英

為什么我的If-Else從不評估為真?

[英]Why does my If-Else never evaluate to true?

我應該計算變量整數“ num”除以其每位數字得到干凈商(余數為0)的次數。

注意:每個數字都被認為是唯一的,因此每次出現相同的可整除數字時都應計數(即:對於222,答案為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
            ++x;

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

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

此函數始終返回0(這就是將變量int“可分割的對象初始化為”),因為用於遞增它的if-else總是計算為false並被跳過。我已經檢查並確保If-Else參數包含有效數字(它們是'是所有整數)。是因為它們都是整數,結果的小數部分永遠不會達到If-Else進行評估嗎?這是我能想到的最佳可能性,即使那樣我也不知道如何補救。

  1. 了解std::string size()函數。 您不需要endbegin獲取string的長度。
  2. numString[x-1]返回一個ASCII碼char ,而不是數字作為數字值。 例如,十進制的0的ASCII碼是48 要獲取一位數字,您可以執行以下操作: numString[x-1] - '0'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM