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.
#include <iomanip>
#include <cmath>
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;
count++;
}
return count;
}
int main()
{
float f = 1;
while (f)
{
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.
}
return 0;
}
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 ".".
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
usingnamespace std;
int main()
{
string f;
cout << "Enter a Number: "; cin >> f;
cout << "Your number has " << count_if( f.begin(), f.end(), ::isdigit ) << " digits\n";
}
I wouldn't bother counting post-decimal-point digits in float or double representation - your number only has finite floating-point accuracy. Try
1 2 3 4 5 6 7 8 9
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
float f = 72.64;
for ( int i = 2; i <= 15; i++ ) cout << fixed << setprecision( i ) << f << '\n';
}