计算十进制 c++ 之后的数字

Counting digit after decimal c++

本文关键字:数字 之后 c++ 十进制 计算      更新时间:2023-10-16

我需要从用户那里获取一个数字作为双精度。 然后,我需要计算小数点后的数字。 我有另一个想法,我可以将小数部分更改为整数。

例如,如果用户输入 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.4440000000001234.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