用cout打印正确的小数点数
我有一个float值的列表,我想打印它们与小数点后两位的cout 。 
例如:
 10.900 should be printed as 10.90 1.000 should be printed as 1.00 122.345 should be printed as 122.34 
我该怎么做?
  ( setprecision似乎没有帮助。) 
 用<iomanip> ,你可以使用std::fixed和std::setprecision 
这是一个例子
 #include <iostream> #include <iomanip> int main() { double d = 122.345; std::cout << std::fixed; std::cout << std::setprecision(2); std::cout << d; } 
你会得到输出
 122.34 
你几乎在那里,也需要使用std :: fixed,请参考http://www.cplusplus.com/reference/iostream/manipulators/fixed/
 #include <iostream> #include <iomanip> int main(int argc, char** argv) { float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 }; std::cout << std::setprecision(2) << std::fixed; for(int i = 0; i < 6; ++i) { std::cout << testme[i] << std::endl; } return 0; } 
输出:
 0.12 1.23 12.35 123.45 1234.50 12345.00 
  setprecision(n)适用于整数,而不是小数部分。 您需要使用定点格式来使其适用于小数部分: setiosflags(ios::fixed) 
简化接受的答案
简单的例子:
 #include <iostream> #include <iomanip> int main() { double d = 122.345; std::cout << std::fixed << std::setprecision(2) << d; } 
你会得到输出
 122.34 
参考:
-  std::fixed
-  std::setprecision
您必须将“浮动模式”设置为固定。
 float num = 15.839; // this will output 15.84 std::cout << std::fixed << "num = " << std::setprecision(2) << num << std::endl; 
要在小数点后面设置固定的2位数,首先使用这些数字:
 cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); 
然后打印你的双值。
这是一个例子:
 #include <iostream> using std::cout; using std::ios; using std::endl; int main(int argc, char *argv[]) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); double d = 10.90; cout << d << endl; return 0; } 
我在编码竞赛中遇到了类似的问题,我就是这样处理的。 将所有double值的精度设置为2
首先添加标题来使用setprecision
 #include <iomanip> 
然后在我们的主要添加下面的代码
  double answer=5.9999; double answer2=5.0000; cout<<setprecision(2)<<fixed; cout <<answer << endl; cout <<answer2 << endl; 
输出:
 5.99 5.00 
你需要使用固定的写5.00这就是为什么,你的输出不会达到5.00。
我要添加一个简短的参考video链接,这是有帮助的
只是一个小点; 把下面的标题
使用命名空间std;
然后
std :: cout << std :: fixed << std :: setprecision(2)<< d;
变得简化了
cout << fixed << setprecision(2)<< d;
我想要一致的格式化时遇到了整数问题。
重写完整性:
 #include <iostream> #include <iomanip> int main() { // floating point formatting example double d = 122.345; cout << std::fixed << std::setprecision(2) << d << endl; // Output: 122.34 // integer formatting example int i = 122; cout << std::fixed << std::setprecision(2) << double(i) << endl; // Output: 122.00 } 
 #include<stdio.h> int main() { double d=15.6464545347; printf("%0.2lf",d); } 
这是一个使用matrix的例子。
 cout<<setprecision(4)<<fixed<<m[i][j]