c++ - 如何以表格形式输出

标签 c++ formatting tabular

谁能帮助我,不知道如何为 Charge-column 输出。我需要在该收费栏下方制作该输出,但每次当我点击 ENTER 时,它都会生成一个新行,因此我的输出出现在新行中。每个输出后还有一个零,不知道它来自哪里。这是我的代码:

#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
float calculateCharges(double x);
int main()
{
    int ranQty; //calculates randomly the quantity of the cars
    double pTime; // parking time
    srand(time(NULL));

    ranQty = 1 + rand() % 5;

    cout << "Car\tHours\tCharge" << endl;

    for(int i = 1; i <= ranQty; i++)
    {
    cout << i << "\t";
    cin >> pTime ;
    cout << "\t" << calculateCharges(pTime) << endl; 

    }
    return 0;  
}
float calculateCharges(double x)
{
    if(x <= 3.0) //less or equals 3h. charge for 2$
    {
        cout << 2 << "$";
    }
    else if(x > 3.0) // bill 50c. for each overtime hour 
    {
        cout << 2 + ((x - 3) * .5) << "$";
    }
}

最佳答案

您每次都按ENTER 键将pTime 从命令行发送到程序的标准输入。这会导致换行。新行是导致控制台首先将您的输入移交给程序的原因。

为了正确打印,您可以简单地将 pTime 存储到数组中(即,最好在 std::vector 中,如 @user4581301 所述);计算所需的并打印出来。 像这样的东西:

#include <vector>

ranQty = 1 + rand() % 5;
std::cout << "Enter " << ranQty << " parking time(s)\n";
std::vector<double> vec(ranQty);
for(double& element: vec) std::cin >> element;

std::cout << "Car\tHours\tCharge" << std::endl;
for(int index = 0; index < ranQty; ++index)
   std::cout << index + 1 << "\t" << vec[index] << "\t" << calculateCharges(vec[index]) << "$" << std::endl;

there is a zero after each output, don't know where is that come from.

float calculateCharges(double x); 这个函数应该返回一个 float 并且你的定义类似于一个 void 函数。解决方案是:

float calculateCharges(double x)
{
   if(x <= 3.0)    return 2.0f;       // --------------> return float
   return 2.0f + ((x - 3.0f) * .5f) ; // --------------> return float
}

关于c++ - 如何以表格形式输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51461972/

相关文章:

C++ 泛型链表

java - 在 SimpleDateFormat 模式字符串中使用字母字符

python - 如何以表格形式和字母顺序打印字典?

html - 在 HTML 中显示表格数据

html - Visual Studio 2010 html 缩进

MySQL复杂合并两个具有不同日期格式的表

c++ - 无法使用 bash 脚本正确重启应用程序

C++ Lambda 表达式 : Capture Clause vs Argument List; what is the crucial difference?

C++ 继承问题,无法调用基类中定义的公共(public)函数

javascript - 在 Javascript 中解析 ISO 8601 日期