Hello so I got this code here to count the number of digits in a number such as 52 has 2 digits or 793 has 3 digits. I just dont understand how to do this with decimaled numbers after the decimal place... such as finding the number of digits for 72.64, It would be 4 digits but my code only says 2. Please Advise.
usingnamespace std; // <--- Best not to use.
int count_digits(int num) // <--- Defining as and "int" you loose the decimal part.
int count = 0;
while (num != 0)
num = num / 10;
float f = 1;
cout << "Enter a Number: ";
cin >> f;
int i = float(f); // <--- This line unnecessary. "f" is already defined as a float and does not need to be type cast. Stuffing a "float" into an "int" loosed the decimal part.
cout << "Number of digits in: " << count_digits(i) << endl; // <--- You can just send "f" to the function.
I would suggest using "double" over "float" unless your decimal numbers are small or you have a storage space problem and need the small variable.
With "f" being a floating point variable you may have a problem with the while condition. The condition, in the end, will convert what is evaluated to bool type meaning the (0) is false and (1) is true. A floating point number may not always be (0.0) or (1.0).
For your function. Define the parameter as a "double" then inside the function convert the number to a string. using "string.find" get the position of the "." then you can use simple math to figure the amount of digits to the left and right of the ".".