Counting digits using while loop

前端 未结 7 593
清酒与你
清酒与你 2021-01-05 10:15

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;            


        
7条回答
  •  没有蜡笔的小新
    2021-01-05 10:36

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

提交回复
热议问题