计算十进制 c++ 之后的数字
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
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 计算十进制 c++ 之后的数字
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何在向量中某个数字之后重新计算进程
- 预期输出之后的所有这些数字是多少
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- C++ 在地板函数之后以十六进制打印数字
- 在每个偶数特定数字之后,插入向量中
- 如何在C ++中打印特定位数的位数?例如,总共打印8位数字(小数点之前+之后的组合)
- C :Bool方法在COUT语句之后返回意外数字
- 小数点之后,如何指定有多少个数字
- C 如何在文件中的特定字符串之后获取数字
- std::queue::size() 可以在 size() == 0 的 pop() 之后返回一个巨大的数字
- 如何从 9 和 90 中提取 2.9 和 2.09,即获取数字等于最大编号的小数部分.二分位数之后的数字
- 默认值仅适用于 8 和 9.之后,它使用第一个数字并将其视为 1,2,3
- 在waitpid()之后来自WTERMSIG宏的异常信号数字
- 如何在第 "." 点之后将数字放入数组中
- 仅读取文本文件中的数字并存储在数组中.之后,读取第一行来存储在数组中
- 在c++中截断数字(点之后)
- 如何在读取文本文件时跳到每行最后一个数字之后的下一行