Counting digits using while loop

2020-03-02 04:53发布

I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:

int x;    
cout << "Enter a number: ";
cin >> x;
x /= 10;
while(x > 0)
{
  count++;
  x = x/10;
}

From what I can tell (even with my limited experience) is that it seems crude and rather unelegant.

Does anyone have an idea on how to improve this code (while not using an inbuilt c++ function)?

7条回答
SAY GOODBYE
2楼-- · 2020-03-02 05:20

If x is an integer, and by "built in function" you aren't excluding logarithms, then you could do

double doub_x=double(x);
double digits=log(abs(doub_x))/log(10.0);
int digits= int(num_digits);
查看更多
贪生不怕死
3楼-- · 2020-03-02 05:21
#include<iostream>
using namespace std;
int main()
{
int count=0;
    double x;
    cout << "Enter a number: ";
    cin >> x;
    x /= 10;
    while(x > 1)
    {
      count++;
      x = x/10;
    }
    cout<<count+1;
}
查看更多
不美不萌又怎样
4楼-- · 2020-03-02 05:28

In your particular example you could read the number as a string and count the number of characters.

But for the general case, you can do it your way or you can use a base-10 logarithm.

Here is the logarithm example:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double n;
    cout << "Enter a number: ";
    cin >> n;

    cout << "Log 10 is " << log10(n) << endl;
    cout << "Digits are " << ceil(log10(fabs(n)+1)) << endl;
    return 0;
}
查看更多
叼着烟拽天下
5楼-- · 2020-03-02 05:33

Given a very pipelined cpu with conditional moves, this example may be quicker:

if (x > 100000000) { x /= 100000000; count += 8; }
if (x > 10000) { x /= 10000; count += 4; }
if (x > 100) { x /= 100; count += 2; }
if (x > 10) { x /= 10; count += 1; }

as it is fully unrolled. A good compiler may also unroll the while loop to a maximum of 10 iterations though.

查看更多
霸刀☆藐视天下
6楼-- · 2020-03-02 05:34

You could read the user input as a string, and then count the characters? (After sanitising and trimming, etc.)

Alternatively, you could get a library to do the hard work for you; convert the value back to a string, and then count the characters:

cin >> x;
stringstream ss;
ss << x;
int len = ss.str().length();
查看更多
ら.Afraid
7楼-- · 2020-03-02 05:41
int count = (x == 0) ? 1 : (int)(std::log10(std::abs((double)(x)))))) + 1;
查看更多
登录 后发表回答