【问题标题】:How to use cout formatting statements to print the input and output in proper format?如何使用 cout 格式化语句以正确的格式打印输入和输出?
【发布时间】:2021-02-20 07:23:07
【问题描述】:

我有一个二维数组,用于存储 X 组的数学和化学数字。下面是我如何为每个类获取输入并将它们存储在每个类的二维数组中。

Input for Maths class:
50 20 30 40 50

Input for Chemistry class:
90 70 20 10 40
  • 现在,根据每个类的上述输入,我需要计算“BEST”、“WORSE”和“AVERAGE”数字。
  • 此外,我还需要计算“数学”和“化学”课程的每组(共 5 组)的平均值,然后在这里也得出总体平均值。

一旦我接受了数学和化学课的上述输入,我需要以下面的格式打印,其中将包含上面第 1 点和第 2 点的数据以及输入-

             1     2     3     4     5    
            *****************************
Math        50.00 20.00 30.00 40.00 50.00 
Chemistry   90.00 70.00 20.00 10.00 40.00

问题陈述

我能够完成上述所有操作并轻松计算第 1 点和第 2 点,但我无法弄清楚如何以上述格式打印输出,以正确格式化的方式显示输入和输出。截至目前,我的程序在输入后将所有内容与不同行中的输出分开打印 -

int main()
{
    double val[2][5];
    //.. val array being populated


    return 0;
}

如何在上面的代码中使用cout.setf(ios::fixed)cout.setf(ios::showpoint)cout.precision(2)cout.width(4); 来获得我需要的格式?

【问题讨论】:

  • 查看{fmt} 进行合理的文本处理。
  • 我正在学习基础知识,所以我想了解如何使用 setfprecisionwidth 函数。一旦我掌握了这一点,我就可以尝试看看其他的东西。
  • 首先,修复你的未定义行为:array[2][5],然后你访问array[2][...]。你只能访问array[0][...]array[1][...]
  • 索引是从0开始的吧? @TedLyngmo 嗯,我明白了
  • 是的,没错。

标签: c++ formatting


【解决方案1】:

这可能是一种方式:

auto w = std::setw(6);   // for number like " 10.00" (6 chars)
auto wb = std::setw(8);  // for the numbers with more space between them
auto sw = std::setw(11); // for titles (math, chemistry)

// print the numbers above
cout << "         ";
for(int i=1; i<=5; ++i) std::cout << w << i;
std::cout << "     BEST    WORST  AVERAGE\n";

// print a line of *
std::cout << sw << "" << std::string(56,'*') << '\n';

cout << std::setprecision(2) << std::fixed; // precision 2, fixed

cout << sw << std::left << "Math" << std::right;
for(auto ms : array[0]) std::cout << w << ms;
cout << wb << math_best << wb << math_worse << wb << math_average << '\n';

cout << sw << std::left << "Chemistry" << std::right;
for(auto cs : array[1]) std::cout << w << cs;
cout << wb << chemistry_best <<  wb << chemistry_worse << wb << chemistry_average << '\n';

输出

              1     2     3     4     5     BEST    WORST  AVERAGE
           ********************************************************
Math        50.00 20.00 30.00 40.00 50.00   50.00   20.00   38.00
Chemistry   90.00 70.00 20.00 10.00 40.00   90.00   10.00   46.00

【讨论】:

  • 不是那种人,但它可能应该是最糟糕的* :-)
  • 感谢您的帮助!让我通过详细阅读来理解这一点。另外我怎样才能得到*****1 2 3 4 5.. 行在它上面?直接打印?
  • @AyxanHaqverdili :-) 可能。我没有重命名。那时我必须包括整个程序。
  • @AndyP ****... 您可以使用std::cout &lt;&lt; std::string(count, '*'); - 然后它将打印与count 一样多的* - 或者您可以使用填充。 1 2 3 4 5 只是一个循环?
  • @AndyP 我加了一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
  • 2020-06-14
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
相关资源
最近更新 更多