C++ 如何以表格形式输出
谁能帮我,我不知道如何为Charge列生成输出。我需要把输出放在电荷列的正下方,但每次我按ENTER键时,它都会生成一个新行,因此我的输出显示在新行中。每次输出后都有一个零,不知道是从哪里来的。这是我的密码:C++ 如何以表格形式输出,c++,formatting,tabular,C++,Formatting,Tabular,谁能帮我,我不知道如何为Charge列生成输出。我需要把输出放在电荷列的正下方,但每次我按ENTER键时,它都会生成一个新行,因此我的输出显示在新行中。每次输出后都有一个零,不知道是从哪里来的。这是我的密码: #include<iostream> #include<stdlib.h> #include<time.h> using namespace std; float calculateCharges(double x); int main() {
#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) << "$";
}
}
#包括
#包括
#包括
使用名称空间std;
浮动计算电荷(双x);
int main()
{
int ranQty;//随机计算车辆数量
双pTime;//停车时间
srand(时间(空));
ranQty=1+rand()%5;
cout您每次都在按ENTER键,将pTime
从命令行发送到程序的标准输入。这会产生一个新行。新行首先会导致控制台将您的输入移交给程序
为了正确打印,您只需将pTime
存储到一个数组(即,如@user4581301所述,最好是在std::vector
中);计算所需的时间并打印它。
比如:
#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;
关于这个额外的零,当一个函数承诺返回一个值,但没有返回时会发生奇怪的事情。calculateCharges
应该返回一个float
,但可能不应该,因为它会为您打印结果。至于您的问题,我没有一个好的解决方案。iostreams太简单了,无法满足您的要求。但是如果读入所有输入,将其存储在向量中,然后计算并打印,就可以接近了。
float calculateCharges(double x)
{
if(x <= 3.0) return 2.0f; // --------------> return float
return 2.0f + ((x - 3.0f) * .5f) ; // --------------> return float
}