C++ C++;无法使用右对齐将双精度校准到2
如何将代码对齐到右侧的3个位置,而不是默认的左侧C++ C++;无法使用右对齐将双精度校准到2,c++,formatting,C++,Formatting,如何将代码对齐到右侧的3个位置,而不是默认的左侧 10.23 100.23 10.23 ----------Like this 100.23 double test = 10.2345; double test2 =100.2345; std::cout << std::setprecision(2) << std::fixed << test << '\n' << test2 << std::endl;
10.23
100.23
10.23 ----------Like this
100.23
double test = 10.2345;
double test2 =100.2345;
std::cout << std::setprecision(2) << std::fixed << test << '\n' << test2 << std::endl;
10.23
100.23
10.23------像这样
100.23
双重测试=10.2345;
双试验2=100.2345;
std::cout首先使用std::cout.width(num)设置输出的宽度
并使用std::right
将输出设置为右侧,如下所示:
#include <iostream>
#include <iomanip>
int main()
{
std::cout.width(6);
std::cout << std::right << 10.23 << std::endl;
std::cout << std::right << 10.453;
return 0;
}
#包括
#包括
int main()
{
标准:计算宽度(6);
std::cout首先使用std::cout.width(num);
设置输出的宽度,然后使用std::right
将输出设置为右侧,如下所示:
#include <iostream>
#include <iomanip>
int main()
{
std::cout.width(6);
std::cout << std::right << 10.23 << std::endl;
std::cout << std::right << 10.453;
return 0;
}
#包括
#包括
int main()
{
标准:计算宽度(6);
std::cout如果您知道精度,那么您只需要找到整数部分中位数最多的数字:
100.2345
^^^
3
我们可以通过log10
来实现这一点。因此,对于您拥有的每个数字,请检查它是负数(由于负号,需要在偏移量中添加一个额外的值)还是正数,并在继续操作时存储最大偏移量
例如:
double nums[]{ -10.2345, 100.2345, 10.2345, 1000.23456 };
int offset = INT_MIN;
int m{ 0 };
for (auto const& i : nums) {
if (i < 0)
m = log10(abs(i)) + 2;
else
m = log10(i) + 1;
if (m > offset) offset = m;
}
瞧
for (auto const& i : nums) {
cout << setprecision(precision) << fixed << setw(offset) << right << i
<< '\n';
}
如果知道精度,则只需找到整数部分中位数最多的数字:
100.2345
^^^
3
我们可以通过log10
来实现这一点。因此,对于您拥有的每个数字,请检查它是负数(由于负号,需要在偏移量中添加一个额外的值)还是正数,并在继续操作时存储最大偏移量
例如:
double nums[]{ -10.2345, 100.2345, 10.2345, 1000.23456 };
int offset = INT_MIN;
int m{ 0 };
for (auto const& i : nums) {
if (i < 0)
m = log10(abs(i)) + 2;
else
m = log10(i) + 1;
if (m > offset) offset = m;
}
瞧
for (auto const& i : nums) {
cout << setprecision(precision) << fixed << setw(offset) << right << i
<< '\n';
}
使用std::right
from
和std::setw
请参见。@dxiv我已经尝试了上述setw和right,但似乎不起作用@Daboss2182您的数字需要宽度>=6。使用std::right
和std::setw
请参见。@dxiv我已经尝试了上述setw和right,但似乎不起作用cout@Daboss2182您的数字需要大于等于6的宽度。