如何计算小数点前后的位数?

时间:2016-06-06 17:58:52

标签: c++ loops decimal-point

今天在我的c ++课程测试中提出了一个问题。 “编写一个输入浮点数的程序,并计算小数点前后的位数。”

我使用此代码计算小数点前的数字:

float n;

cin>>n;

float temp = n;

int count = 0;

while(temp1 > 1) {

    count++;

    temp = temp/10;
}

cout<<count;

但是我坚持了一下。谁能告诉我怎么做?或者可以提供整个程序?

提前致谢,

2 个答案:

答案 0 :(得分:5)

  

编写一个输入浮点数的程序,并计算小数点前后的位数。

好吧,因为该任务要求使用float和标准c ++不能真正解决的问题,因为float值指数和尾数的二进制表示不是在c ++标准。
因此,除非您知道c ++编译器如何实现float(或double)二进制表示,否则您无法知道将使用多少位来表示数字的小数部分。

最有可能的是,实现针对目标CPU及其处理浮点值的能力进行了优化。

所以你唯一的机会就是在第一位读取数字std::string表示,计算'.'字符前后出现的数字,最后转换{{1}变量为std::string值。

这里简单说明了我在答案的第一部分中的含义:

float

输出

#include <iostream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <sstream>

int main() {

    std::istringstream iss("3.1415"); // same as reading from cin
    std::cout << "Input: " << iss.str() << std::endl;
    float temp;
    iss >> temp;
    std::cout << "Internal representation: " 
              << std::fixed << std::setprecision(22) << temp << std::endl;
    float fraction = temp - abs(temp);
    int fractiondigits = 0;
    while(fraction > std::numeric_limits<float>::epsilon()) { // epsilon is the smallest 
                                                              // value that can be 
                                                              // represented in binary form
        fraction *= 10.0f;
        fraction -= abs(fraction);
        ++fractiondigits;            
    }
    std::cout << "Number of digits used in the representation: " 
              << fractiondigits << std::endl;
}

Live Demo

所以你发现这与用户的输入不一致。

我不知道您的教授是否打算询问并让您承认用户输入和Input: 3.1415 Internal representation: 3.1414999961853027343750 Number of fraction digits used in the representation: 21 的内部表示的不一致。
但如上所述,实际的位数是编译器实现和平台相关的,因此对小数位数没有明确的答案。

答案 1 :(得分:0)

问题基本上是无关紧要。大多数实数具有无限多个数字,但计算机表示的数字必须具有有限的表示。对于二进制表示的常见情况,所表示的数字也具有有限的十进制表示。但是,将此十进制表示截断为较少的数字(尽管精确到std::numeric_limits<float>::max_digits10)仍然可以获得相同的可表示数字。因此,计算机浮点数的相关位数最好是指它们的二进制而不是它们的十进制表示。这由std::numeric_limits<float>::digits给出(总数:在该点之前和之后)。