简体   繁体   中英

Count the length of a number

Hello I would like to count the number there is in a number I mean if I have this double 78.23 the functions would return 4 if I have 145.123 I would got 6. Is it possible to do this with C++ ? Thank you !

Precision - in the sense that you are asking about it - is as much a property of the output stream, as of the value being output. Assuming you are outputting using an C++ ostream ( ofstream , ostrstream , etc), look up properties ios_base::precision , ios_base::width , etc or stream manipulator like setprecision . If you are using CI/O ( sprintf() , etc), the answer depends upon modifiers specified for the %f format.

So the method to get the value you seek would probably be to output the value using your chosen method (stream manipulators, format specifiers) to a string. Then compute the length of the string, subtract one for every trailing 0 , the decimal point, etc.

Also, floating point variables with a base 2 mantissa (which includes most real-world floating point representations) cannot exactly represent any value that is not a sum of integral powers of 0.5 (the stored value is an approximation). Among other things, this means a floating point variable cannot exactly represent values like 0.1 and 0.01 . Both of your sample values 78.23 and 145.123 cannot be represented exactly using floating point variables. Which is part of the reason why the answer to questions like yours depends on how the variable is output, as much as the value itself.

the easy way of doing this is to just enter the number as a string and use .length()

#include <iostream>
#include <string>
#include <conio.h>
using namespace std; int main() {

string number;

cout << "Enter a number: ";
cin >> number;

cout << "length is " << number.length();

_getch(); 
return 0; 

if you need it strictly to be with integers and doubles then you'll have to create a mathematical algorithm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM