0

正如标题所说,我必须找出给定数字中的位数。这是我的代码,当数字超过 10 时,我的结果为 0 在 Visual Studio Pro 2012 中编程

代码:

#include <iostream>
using namespace std;

int main()
{
    int g, count=0;

    cout << "Enter the number" << endl;
    cin >> g;

    while (g > 0)
    {
        count = count +1;
        g = g/10;
    }
    cout << count << endl;

    system ("pause");
    return 0;
}
4

5 回答 5

3

你有没有做任何调试?

你认为 g 的多少值会使这个条件成立?

(g > 0 && g <= 10) 

这应该足以让您找出问题所在。

于 2013-10-09T06:07:57.697 回答
1

如果 g > 10,则

(g > 0 && g<=10)是假的。

于 2013-10-09T06:07:05.717 回答
0

先把一个字符串转成int,然后再找它的长度,有点麻烦。你为什么不只看字符串?

#include <iostream>
#include <string>

int main()
{
  std::cout << "Enter the number" << std::endl;

  std::string g;
  std::cin >> g;

  std::cout << g.size() << "\n";
}

注意:这不会修剪前导零;我把这个留给你。

于 2013-10-09T06:21:33.127 回答
0

如果您真的想为此使用循环(log10-call 可以完成这项工作),请使用类似这样的内容(未经测试):

for (count=0;g>0;g/=10,count++) {}

这与您编写的几乎相同,但没有 - 条件g<10

于 2013-10-09T06:10:54.540 回答
0

此代码将重现位数。

#include <iostream>

using namespace std;
int main()
{
    int g, count=0;
    cout << "Enter the number" << endl;
    cin >> g;
    while (g > 0)
    {
        count = count +1;
        g /= 10;
    }
    cout << count << endl;
    return 0;
}

除此之外,还有另一种方法可以解决这个问题

#include <iostream>
#include <cmath>

using namespace std;
int main()
{
    int g, count=0;
    cout << "Enter the number" << endl;
    cin >> g;
    count = (int)(log10((double)g));
    if (g == 0)
        count = 0;
    cout << count + 1 << endl;
    return 0;
}
于 2013-10-09T06:08:35.313 回答