小数点之后,如何指定有多少个数字
How can I specify how many numbers are there after decimal point?
是否有任何方法可以确定小数点后我的双重数中有多少个数字。例如double a=3.14259
如果我现在制作新的int b
,如何使b
的值等于a
之后的数字?
简短的答案是,您不能。
首先,在(二进制)期之后,像double
这样的类型始终具有相同数量的二进制数字。这就是称为Mantissa。如果两倍为53位,则意味着二进制期后52位,小数点约为15位。有关详细信息,您可能会看到IEEE_754(双精度)
当您将双重转换为十进制字符串时,通常您将永远不会匹配十进制。例如,值0.1
不能完全由双重值表示。应用舍入后可能显示" 0.1"。
但是,当您处理一些双重计算时,您会遇到诸如0.10000000000012
或0.09999999999987
之类的小派生。在这种情况下,您将做什么?
和一个数学问题,与C 双打无关:
_
0.1 is equal to 0.09
所以您的答案将为1或Infinity
这是一种方法:将小数转换为字符串,并在小数点后找到子字符串的大小,如下:
#include <iostream>
#include <string>
int main()
{
double a = 3.14259;
std::string a_string = std::to_string(a);
a_string.erase ( a_string.find_last_not_of('0') + 1, std::string::npos ); //Get rid
//of extra zeroes
std::cout << a_string.substr(a_string.find('.') + 1).size() << "n";
//Print the size of the substring of the original string from the decimal point (here 5)
}
您可以将分数部分视为字符串文字。利用std :: stringstream和std :: string:
#include <iostream>
#include <string>
#include <sstream>
int main(){
double whole = 3.14259;
auto fractionalno = whole - static_cast<long>(whole); // or use std::modf()
std::stringstream ss;
ss << fractionalno;
std::string s = ss.str();
s.erase(0,2);
std::cout << "The number of digits is: " << s.size();
}
浮点数在点之后不提供数字数。(这甚至不是"确切"值。它是一个近似值。)
但是,如果您只想制作另一个整数以在屏幕上的点之后具有相同数量的数字,为什么不算数?
这是Python代码:
a = 4.0 / 7
# a is 0.5714285714285714
b = str(a)
# b (str(a)) is 0.571428571429, different with a.
nod = len(b[b.index('.'):])
_c = 9.0 / 7
c = float(int(_c * 10 ** nod)) / 10 ** nod
相关文章:
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 如果我不知道每个列表中有多少个数字,我如何将给定数量的数字列表作为输入?
- C++ 检查结果数组中有多少次数字
- 如何计算整数链中使用了多少次数字?
- 预期输出之后的所有这些数字是多少
- 随机生成的输出中有多少位数字 1、2、3
- 0 和 n 之间有多少个数字满足按位属性 i&y==i?
- 给定 N 个范围.有多少种方法可以从这些范围中获取 N 个数字,这些数字的总和达到某个值
- N 阶乘中有多少位数字
- 小数点之后,如何指定有多少个数字
- 当用户确定将输入多少个数字时,需要程序来乘以用户输入
- 数字 0ui64 是多少
- 从序列中减去一个数字后,剩余的数字中有多少是正数
- 猜数字:计算机要猜多少次才能得到正确的数字
- N个整数与K对数字有多少个不能相邻的排列?
- 二进制表示中数字的偶数位和奇数位的 1 数是多少?
- 找出一个特定整数有多少个二进制数字
- 给定一系列数字报告,哪些重复和重复了多少次
- 如何计算每个数字遇到了多少次