0

Hello I am trying to count the number of digits in a given double. I am encountering an infinite loop doing so. I tried to isolate each while statement and it works fine but when I combine them I am having an infinite loop on a the second while condition. here's the code

#include <iostream>
using namespace std;

int main()
{
//Counting digits of a number
double N, M, b;
int i, j, a;

cout << "This program will count how many digits the given whole number has.\n\n";
cout << "Please enter the Number: "; // N = 123.567 Digits should be = 6
    cin >> N;
    a = (int)N;
    M = N - a;
    b = M - int(M);
    j = 0;
     
    if (a == 0 && b == 0)
        cout << "You have entered number 0.";
    else
    {
        i = 0;
        j = 0;
        while (a > 0) //for the integer (whole number) part of the number
        {
            a /= 10;
            i++;
        }
        while (b != 0) //for the fractional part of the number 
        {
            j++;
            M *= 10;
            b = M - int(M);
        }
        cout << "Display i: " << i << endl; // i = number of whole number digits
        cout << "Display j: " << j << endl; // j = number of fractional digits
    }
    system("pause > 0");

}

  • Also, you can replace the initial calculations with [`modf()`](https://www.cplusplus.com/reference/cmath/modf/), although you'll still have the floating-point issue. – Ken Y-N Mar 14 '22 at 06:07
  • I tried setting N = 1.123 and it works but when I try 1.12, 2.123 or any other number - it gives infinite loop for some reason – Amil Josiah Estornino Mar 14 '22 at 06:16
  • 1
    `while (b != 0)` should be `while (b > 0.00001)` or something like that because `2.123` is actually stored as `2.1230000000000002` - you really need to read that link in the comment by @KenY-N – Jerry Jeremiah Mar 14 '22 at 06:21
  • Yes I did read it, I really need to set my tolerance to solve this problem. will think more how to solve this problem - I just started learning C++ and this is one of the basics. Thanks – Amil Josiah Estornino Mar 14 '22 at 06:33
  • Floating-point values don't have decimal digits. They have binary digits, and the two are incommensurable. Your question doesn't make sense. – user207421 Mar 14 '22 at 08:42
  • "count the number of digits" only *sounds* like a numeric operation. It's really a string operation and operating on double/float/whatever is not logical and only serves to reduce precision and add complexity for no benefit. – tenfour Mar 14 '22 at 10:04

2 Answers2

1

As a double stores fraction parts to a more significant extent, you cannot count digits in a double in this way. Instead,

  1. Accept the number as a string.
  2. Convert it to double using stod()
  3. Step2 is to make sure the user has entered the number as if it's other than the number it'll give an exception.
  4. Count digits in the string.

Here is what it will look like

#include<iostream>
#include<string.h>
using namespace std;

int main(){
    
    string str = "";
    cin>>str;
    int counter =0;
    try{
        double d = stod(str);
        for(int i=0;i<str.length();i++){
            if(str.at(i) >= '0' && str.at(i) <= '9')
                counter++;
        }   
        cout<<counter;
    }
    catch(...){
        cout<<"Please enter only numbers";
    }
    
    
    return 0;
}

I have used catch which is general, meaning it will catch all exceptions. You can use specific exception too.

Shivam Papat
  • 457
  • 4
  • 14
1

Using a floating point type at any point in this analysis is not the correct thing to do. That's because (like an integral type) they can only store a subset of the real number set.

A good approach here would be to read the input as a string, check that it is a plausible number (e.g. does it contain only one decimal separator)? Write something clever to trim any zeros after the decimal separator and leading zeros before the number, allow for a negative sign, then count the digits.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Agree. Also, he wants to get only the count of digits of the number and the number is user input, so we probably don't need much to think about trailing zeros. But to might be the case that the user entered a long string of decimal numbers. – Shivam Papat Mar 14 '22 at 08:34