[英]Counting digit after decimal c++
我需要从用户那里获得一个双号。 然后,我需要计算小数点后的位数。 我有另一个想法,我可以将小数部分更改为整数。
例如,如果用户输入234.444,则使用此方法,我将从该值中分离出0.444
double usereneteredvalue=234.444;
int value2=userenteredvalue;
double decimalvalue=userenteredvalue-value2;
但是然后我需要将0.444转换为444,这是我做不到的,因为我不知道十进制后用户输入了多少个值。 谁能给我个主意?
将用户输入输入字符串,如下所示:
std::string string;
std::cin >> string;
然后
std::istringstream s(string);
int before, after;
char point;
s >> before >> point >> after;
有一个在你的电话号码after
现在。
编辑:确定更好的解决方案后,使用数字来确定位数
int number_of_digits = string.size() - string.find_last_of('.');
“使用double
精度输入”的问题在于, double
精度不会在该点之后存储用户定义的位数。 换句话说,您的234.444
实际上可能类似于234.4440000000001
或234.443999999999999
。
您已经有了一个很棒的C ++风格的解决方案 ,但是从此注释看来,您似乎不喜欢字符串。
如果您真的不想使用字符串,它将非常难看。 这将在大多数时间*起作用:
//Chop the left side of the decimal off, leaving only the right side
double chop_integer(double d) {
return d - static_cast<int>(d);
}
...
double some_value;
//We don't really care about the integer part, since we're counting decimals,
// so just chop it off to start
some_value = chop_integer(some_value);
int num_after_dec = 0; //initialize counter
//some_value != 0 won't work since it's a double, so check if it's *close* to 0
while(abs(some_value) > 0.000000001) {
num_after_dec++;
//Move decimal right a digit and re-chop the left side
some_value *= 10;
some_value = chop_integer(some_value);
}
std::cout << num_after_dec << std::endl;
*双打根本无法准确存储某些数字,因此,诸如.111
类的操作将失败
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.