如何以表格形式输出

How to make the output in tabular form

本文关键字:输出 表格      更新时间:2023-10-16

谁能帮我,却不知道如何为Charge列输出。我需要在电荷列下进行输出,但每次当我点击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 << "CartHourstCharge" << 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 << "CartHourstCharge" << 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
}