如何以表格形式输出

问题描述 投票:1回答:1

谁可以帮助我,无法弄清楚如何为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) << "$";
    }
}
c++ formatting tabular
1个回答
1
投票

您每次都要按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;

每次输出后都有一个零,不知道它来自哪里。

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
}
© www.soinside.com 2019 - 2024. All rights reserved.