Counting numbers using a while loop

Recently, I created a program that was supposed to check the number of digits in the amount entered 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 say (even with my limited experience), is that he seems rude and rather inelegant.

Does anyone have an idea on how to improve this code (without using the built-in C ++ function)?

+6
source share
7 answers

In your specific example, you can read the number as a string and count the number of characters.

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

Here is an example of a logarithm:

 #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; } 
+11
source
 int count = (x == 0) ? 1 : (int)(std::log10(std::abs((double)(x)))))) + 1; 
+5
source

Can you read the user input as a string and then count the characters? (After disinfection and trimming, etc.)

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

 cin >> x; stringstream ss; ss << x; int len = ss.str().length(); 
+2
source

If x is an integer, and the "built-in function" you do not exclude the logarithms, you can do

 double doub_x=double(x); double digits=log(abs(doub_x))/log(10.0); int digits= int(num_digits); 
+1
source

Given a very pipelined processor with conditional moves, this example might be faster:

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

since it is fully deployed. A good compiler can also expand a while loop to a maximum of 10 iterations.

+1
source
 #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; } 
0
source

Make suggestions for reading the numbers as a string, your current method of counting the number of significant decimal digits is excellent. You can make it shorter, but it may be less clear (an additional set of brackets has been added so that gcc does not give warnings):

 while((x = x/10)) count++; 
-1
source

Source: https://habr.com/ru/post/892165/


All Articles