小数点之后,如何指定有多少个数字

How can I specify how many numbers are there after decimal point?

本文关键字:多少 数字 何指定 之后 小数点      更新时间:2023-10-16

是否有任何方法可以确定小数点后我的双重数中有多少个数字。例如double a=3.14259

如果我现在制作新的int b,如何使b的值等于a之后的数字?

简短的答案是,您不能。

首先,在(二进制)期之后,像double这样的类型始终具有相同数量的二进制数字。这就是称为Mantissa。如果两倍为53位,则意味着二进制期后52位,小数点约为15位。有关详细信息,您可能会看到IEEE_754(双精度)

当您将双重转换为十进制字符串时,通常您将永远不会匹配十进制。例如,值0.1不能完全由双重值表示。应用舍入后可能显示" 0.1"。

但是,当您处理一些双重计算时,您会遇到诸如0.100000000000120.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