C++ 中的数字计数器

Digits counter in c++

本文关键字:计数器 数字 C++      更新时间:2023-10-16

正如标题所说,我必须找出给定数字中的位数。这是我的代码,当数字超过 10 时,它给我的结果为 0Visual 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;
}

你做过任何调试吗?

你认为g的什么值会使这个条件成立?

(g > 0 && g <= 10) 

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

如果 g> 10,则

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

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

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

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

此代码将重现位数。

#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;
}

首先将字符串转换为 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";
}

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