代码之家  ›  专栏  ›  技术社区  ›  Satbir

从字符串读取浮点值,精度达到6

  •  0
  • Satbir  · 技术社区  · 15 年前

    我必须从字符串中读取一个精度高达6的flot值,当前代码只读取前6位数字。提前谢谢

    template <class T>
    bool from_string(T& t,    const std::string& s, 
                     std::ios_base& (*f)(std::ios_base&))
    {
      std::istringstream iss(s);
      return !(iss >> f >> t).fail();
    }
    
    int main()
    {
      int i;
      float f;
     // the third parameter of from_string() should be 
      // one of std::hex, std::dec or std::oct
      if(from_string<int>(i, std::string("ff"), std::hex))
      {
        std::cout << i << std::endl;
      }
      else
      {
        std::cout << "from_string failed" << std::endl;
      }
    
      if(from_string<float>(f, std::string("1456.909"), std::dec))
      {
        std::cout << f << std::endl;
      }
      else
      {
        std::cout << "from_string failed" << std::endl;
      }
      return 0;
    } 
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   MSalters    15 年前

    我很确定它能读出所有的数字。问题似乎出在你的预料之中。让我们把它再加强一点:如果你读到 1456.90900000000000000000000000000 在一个 float ?

        2
  •  1
  •   Rob Charlton    15 年前

    如果你想做得比6位数更好,你需要使用双精度,而不是浮点。你的问题是说“6位数的精度”和“前6位数”,但你提供的是7位数的输入。

    浮点数只能保持6位精度,即x.yzpqrs或xy.zpqrs或xyzpq.rs。 小数位数 然后你需要用双份的。

    例如,通过使用cout.precision(7),您可以使它输出更多的小数位,在本例中,它将打印正确的答案,即使C实际上没有存储7位数字,只是一些接近正确答案的数字。