00003 %.nf 设-6ren">
gpt4 book ai didi

c++ - 在 C++ 中使用 C 的各种格式说明符

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:19 25 4
gpt4 key购买 nike

与在 c 中一样,我们可以使用各种格式说明符,例如

  • %nd 其中 n 是一个数字,打印至少覆盖 n 个空间的数字
  • %0nd 同上,除了用 0 预填充 "%05d ",3 => 00003
  • %.nf 设置小数点后 n 的精度
  • 等....

那么有什么方法可以将它们与 std::cout 一起使用吗?

我在 coursera 的最近一门类(class)(c++ for c 程序员)中收到了一些负面反馈,因为我想使用 printf 而不是 cout :(

最佳答案

对于 %nd %0nd,C++ 等效项是 std::setw()std::setfill().

#include <iostream>     // std::cout, std::endl
#include <iomanip> // std::setfill, std::setw

int main () {
std::cout << std::setfill ('x') << std::setw (10);
std::cout << 77 << std::endl;
return 0;
}

输出:xxxxxxxx77

%.nf可以用std::setprecisionstd::fixed代替,

#include <iostream>     // std::cout, std::fixed, std::scientific

int main () {
double a = 3.1415926534;
double b = 2006.0;
double c = 1.0e-10;

std::cout.precision(5);

std::cout << "fixed:\n" << std::fixed;
std::cout << a << '\n' << b << '\n' << c << '\n';
return 0;
}

输出:

fixed:
3.14159
2006.00000
0.00000

关于c++ - 在 C++ 中使用 C 的各种格式说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20539608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com