【问题标题】:How to make the output in tabular form如何以表格形式输出
【发布时间】:2018-07-22 04:11:54
【问题描述】:

谁能帮助我,不知道如何为 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) << "$";
    }
}

【问题讨论】:

  • 关于那个额外的零,当一个函数承诺返回一个值但没有返回时,会发生奇怪的事情。 calculateCharges 应该返回 float,但也许它不应该返回,因为它会为您打印结果。
  • 至于你的问题,我没有好的解决办法。 iostreams 太简单了,无法做你想做的事。但是如果你读入所有的输入,把它存储在一个向量中,然后计算和打印你就可以接近了。

标签: c++ formatting tabular


【解决方案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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 2018-01-10
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多