在c++中控制浮点数的精度

Control the Precision of float number in a C++

本文关键字:精度 浮点数 控制 c++      更新时间:2023-10-16

我试图控制我在字符串中添加的数字数量,但我无法控制它,因为我正在打印字符串数组。

float loads[n] = { 1,2,3,0.05,1,2,3,0.5,1,2,3,3,1,2 };
string print[nBits] = { "" };
int n=14;
int BB;
.
.
.
void main(){
 for (int j = 0; j < nBits; ++j)// 2^n
   {     
         for (int i = 0; i < n; ++i) // n
        {
            BB = arr[j][i];
            R = loads[i];
            if (BB == 1) {
            print[j]+="" +std::to_string(loads[i])+"//";
        }
   }
}

但我最终得到一个字符串数组,看起来像这样:

0.050000//3.000000//…

在将浮点数添加到字符串之前,是否有任何方法可以控制其精度?

(所以我可以有一个结果字符串控制固定数量的数字,而不是)

0.05//3.00//…

std::stringstreamstd::fixedstd::setprecision(n)一起使用

http://en.cppreference.com/w/cpp/io/manip

你可以使用标准的流机制:

您可以使用ostream生成字符串:

#include <ostream>
#include <sstream>
#include <iomanip>
std::ostringstream stream;
for(...) {
   stream << loads[i] << "//";
}
std::string str =  stream.str();

这个想法是生成一个流,你也可以流字符串。然后,您可以使用stream.str()从中生成std::string。流具有如何转换数字的默认值。您可以使用std::setprecisionstd::fixed以及其他变量来影响这一点(有关更多信息,请参阅c++ stdlib参考)。

使用std::setprecisionstd::fixed .

std::ostringstream stream;
// set the precision of the stream to 2 and say we want fixed decimals, not
// scientific or other representations.
stream << std::setprecision(2) << std::fixed;
for(...) {
   stream << loads[i] << "//";
}
std::string str =  stream.str();

你可以在这里找到另一个例子。

sprintf

你总是可以用C的方式,使用sprintf,尽管这是不鼓励的,因为你必须提供一个正确长度的缓冲区,例如:

char buf[50];
if (snprintf(buf, 50, "%.2f", loads[i]) > 0) {
   std::string s(buf);
}