【问题标题】:Why does my If-Else never evaluate to true?为什么我的 If-Else 永远不会评估为真?
【发布时间】:2017-01-13 03:32:16
【问题描述】:

我应该计算变量整数“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 "divisible 被初始化为的值),因为用于递增它的 if-else 总是计算为 false 并被跳过。我已经检查并确保 If-Else 参数包含有效数字(它们都是整数)。是不是因为它们都是整数,结果的小数部分永远不会到达 If-Else 进行评估?这是我能想到的最好的可能性,即使那样我也不知道如何补救措施。

【问题讨论】:

  • 你有一个字符串。字符串包含字符。字符(即使它们是数字)不是数字。 0 != '0'.
  • 您使用的是 IDE 吗?您可以创建一个变量int test = num % numString[x - 1]; 并查看测试等于什么
  • @VictorTran 我使用 222 作为 num 并且测试返回 22,这是..weird
  • @Someprogrammerdude 我怎样才能干净地将这些字符串转换为整数?
  • @WillNjun​​dong 我不认为它比你的更痛苦(但我承认我可以拆分一些指令以使初学者更清楚) - 你的代码涉及迭代器,类似数组的对象(@ 987654324@) 以及数字字符和整数之间的转换 ('0' - 0) - 我的代码只涉及简单的 for 循环和简单的算术。我需要任何 C++ 书籍的一些章节来理解您的代码,而任何这些书籍的第一章都涵盖了理解我的代码所需的所有内容。

标签: c++ c++11 if-statement


【解决方案1】:
  1. 了解size()std::string 功能。您不需要endbegin 来获取string 的长度。
  2. numString[x-1] 返回一个 char 一个 ASCII 码,而不是作为数值的数字。例如,十进制的0 的ASCII 码是48。要获取单个数字的数值,您可以执行以下操作: numString[x-1] - '0'

【讨论】:

  • 我想我之前尝试过类似的方法,以及 variable.length 并得到了不合理的数字。根据我在网上学到的知识,我认为它们是内存大小或其他东西
  • string::length 返回与size() 相同的字符串中的字节数。指向length doc 的链接。您将通过string::capacity 获得内存大小
猜你喜欢
  • 1970-01-01
  • 2016-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 2011-10-25
  • 2015-12-07
相关资源
最近更新 更多