Who could help me, can't figure out how to make my output for Charge-column. I need to make that output right under that charge column, but every time when I hit ENTER it makes a new line hence my output appears in new line. Also there is a zero after each output, don't know where is that come from. Here is my code:
#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) << "$";
}
}
You are hitting ENTER key each time to send your pTime
from the command line to your program's standard input. This causes a new line. The new line is what causes the console to hand your input over to the program in the first place.
In order to print properly, you can simply store the pTime
to an array(i.e, preferably in std::vector
, as @user4581301 mentioned); calculate the required and print it.
something like:
#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);
this function should return a float
and your definition is something like a void function. Solution is:
float calculateCharges(double x)
{
if(x <= 3.0) return 2.0f; // --------------> return float
return 2.0f + ((x - 3.0f) * .5f) ; // --------------> return float
}