【发布时间】: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 我怎样才能干净地将这些字符串转换为整数?
-
@WillNjundong 我不认为它比你的更痛苦(但我承认我可以拆分一些指令以使初学者更清楚) - 你的代码涉及迭代器,类似数组的对象(@ 987654324@) 以及数字字符和整数之间的转换 (
'0' - 0) - 我的代码只涉及简单的for循环和简单的算术。我需要任何 C++ 书籍的一些章节来理解您的代码,而任何这些书籍的第一章都涵盖了理解我的代码所需的所有内容。
标签: c++ c++11 if-statement