【发布时间】:2021-01-03 21:40:09
【问题描述】:
所以我试图找到给定 int 中的位数。我选择查找数字的方法是将给定的 int 除以 10 的幂。由于我将除以整数,因此当 10 提高到足够高的幂时,代码最终会达到 0。会有一个跟踪器跟踪此迭代的每次迭代,并且该跟踪器将能够告诉我有多少数字。
#include <cmath>
#include <iostream>
int findDigits(int x)
{
//tracks the digits of int
int power{ 0 };
for (int i = 0; x / pow(10, i) != 0; i++) //the condition is not working as it should
{
//I checked the math expression and it is getting the intended result of zero at i = 3
int quotient = x / pow(10, i);
//I then checked the condition and it is becoming false when the expression results in 0
bool doesWork;
if (x / pow(10, i) != 0)
doesWork = true;
else
doesWork = false;
power = i;
}
return power;
}
int main()
{
std::cout << "157 has " << findDigits(157) << " digits";
return 0;
}
【问题讨论】:
-
简单得多:不断除以 10,直到结果为 0。
-
那么问题出在哪里?请描述它(包括预期和实际输出)。
标签: c++ for-loop visual-c++ integer c++17