C+中的浮点格式+; 如何将C++中的浮点格式化为输出到两个小数点的四舍五入?我在setw和setprecision方面运气不佳,因为我的编译器刚刚告诉我它们是未定义的

C+中的浮点格式+; 如何将C++中的浮点格式化为输出到两个小数点的四舍五入?我在setw和setprecision方面运气不佳,因为我的编译器刚刚告诉我它们是未定义的,c++,floating-point,cout,C++,Floating Point,Cout,cout您需要包括并为setw和setprecision提供命名空间范围 #include <iomanip> std::setw(2) std::setprecision(5) #包括 标准::setw(2) 标准::设定精度(5) 尝试: 计算精度(5); cout如果要从四舍五入中得到尾随零,可以使用C函数printf #include <iostream> #include <cstdio> int main() { float v =

cout您需要包括
并为
setw和setprecision提供命名空间范围

#include <iomanip>
std::setw(2)
std::setprecision(5)
#包括
标准::setw(2)
标准::设定精度(5)
尝试:

计算精度(5);

cout如果要从四舍五入中得到尾随零,可以使用C函数
printf

#include <iostream>
#include <cstdio>

int main() {
    float v = 12.3961;
    std::printf("%.2f",v); //prints 12.40
}
#包括
#包括
int main(){
浮动v=12.3961;
标准::printf(“%.2f”,v);//打印12.40
}
与之相比:

#include <iostream>
#include <iomanip>

int main() {
    float v = 12.3961;
    std::cout << std::setprecision(4) << v; //prints 12.4
}
#包括
#包括
int main(){
浮动v=12.3961;

std::cout要同时包含尾随零,设置精度是不够的。您还必须将浮点格式更改为固定格式,该格式使用
setprecision
所述的位数作为小数点后的位数:


std::cout使用
cout这有点脏

template <typename T>
string sFormat(const char *f, T value)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), f, value);
    return string(buffer);
}
模板
字符串格式(常量字符*f,T值)
{
字符缓冲区[64];
snprintf(buffer,sizeof(buffer),f,value);
返回字符串(缓冲区);
}
这样做:

cout << "Result :" << sFormat(" %5.2f", 3.14) << sFormat(" %5d", 2300) << endl;
cout您可以使用C++20来实现:


std::真糟糕,忘了它并编辑了它。没有其他方法可以在不包含其他库的情况下格式化它吗?我问这个问题是因为我的教授非常严格,我假设他不希望我们探索比我们在课堂上学过的库更多的库,比如
iostream
cstring
setprecision(2)显示<代码> 12 < /代码>不<代码> 12.39 <代码>。如何显示小数?@ EVEO <代码> <代码>是C++标准库的一部分。好教授不应禁止您在因特网上探索好的解决方案。如果您能解释为什么您包括标准库的另一个文件(它不是另一个库),应该很好。@eveo这(
12
而不是
12.39
)是因为
setprecision
定义了(默认值)有效位数,而不是小数点后的位数。请注意,对于较大的值,它将使用指数形式。如果您总是希望小数点后有两位数,就像我的情况一样,您必须使用固定数字格式(也可以将
std::fixed
写入
std::cout
)LeMES他问我如何得到精确的输出。是不是?至少我是这样读的。Hmm.。我认为这是我的错误。你的答案是正确的。但是,我不喜欢你想回到C函数,比如<代码> Prtff<代码>。你的C++解决方案D。oesn没有按他希望的那样打印正确的输出(尾随0)。[顺便说一下:你说的是前导而不是尾随]“利米斯是的,我不喜欢使用C函数,但是对于格式化的浮点输入,它比 STD::StestOpkest好得多。”RAPTZ,这就是我正在寻找的意见,我同意你的看法。奇怪的是C++没有比我们的老朋友要好的方法。
std::cout << std::fixed << std::setprecision(2) << v;
#include <iostream>

int main()
{
   using namespace std;

   float loge = 2.718;
   double fake = 1234567.818;
   cout << fixed;
   cout.precision(2);
   cout << "loge(2) = " << loge << endl;
   cout << "fake(2) = " << fake << endl;
   cout.precision(3);
   cout << "loge(3) = " << loge << endl;
   cout << "fake(3) = " << fake << endl;
}
template <typename T>
string sFormat(const char *f, T value)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), f, value);
    return string(buffer);
}
cout << "Result :" << sFormat(" %5.2f", 3.14) << sFormat(" %5d", 2300) << endl;
#include <fmt/core.h>

int main() {
  fmt::print("Total     : {:.2f}\n", 12.3961);
}
Total     : 12.40