如何以表格形式输出
How to make the output in tabular form
谁能帮我,却不知道如何为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
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 如何以表格形式输出
- 如何连接C++和Excel(从C++程序输出到Excel电子表格)
- 如何将用户输入格式化为整洁的表格,以便在C++中输出
- 用于表格输出的库,可自动处理列宽
- c++ -输出结果到xlsx(电子表格)而不是CSV