谁能帮助我,不知道如何为 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/