How to make the output in tabular form - c++

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
}

Related

C++ Variables not updating in loop

For some reason the values in the loop do not update. Instead of taking the new values they are assigned in the loop they stay the same as when first assigned. Why is this?
using namespace std;
int main() {
int town_A_Pop;
int town_A_Growth;
int town_B_Pop;
int town_B_Growth;
int years = 0;
cout << "Enter the polulation of town A and of town B:" << endl;
cin >> town_A_Pop >> town_B_Pop;
cout << "Enter the growth rate of town A and of town B:" << endl;
cin >> town_A_Growth >> town_B_Growth;
do {
town_A_Pop = town_A_Pop * (1 + (town_A_Growth / 100));
cout << town_A_Pop << endl;
town_B_Pop = town_B_Pop * (1 + (town_B_Growth / 100));
cout << town_B_Pop << endl;
years++;
}
while (town_A_Pop < town_B_pop);
cout << "It took " << years << " years for Town A to overtake Town B." << endl;
cout << "Town A Population: " << town_A_Pop << endl;
cout << "Town B Population: " << town_B_Pop << endl;
return 0;
}
I assume that town_A_Pop and town_B_Pop don't update.
If town_A_Growth is less than 100(and greater or same than 0) then (town_A_Growth / 100) will evaluate to 0 and (1 + (town_A_Growth / 100)) will evaluate to 1.
In that case, town_A_Pop = town_A_Pop * 1 so it will stay same.
Same goes to town_B_Pop.
To fix the problem, you can change variables into float or double, or multiply first then divide by 100 like below:
do {
town_A_Pop = (town_A_Pop * (100 + town_A_Growth)) / 100;
cout << town_A_Pop << endl;
town_B_Pop = (town_B_Pop * (100 + town_B_Growth)) / 100;
cout << town_B_Pop << endl;
years++;
}
while (town_A_Pop < town_B_pop);
It will still won't get bigger if both population and growth are too small, though.
Your problem is Type Variables Error
int town_A_Pop;
int town_A_Growth;
int town_B_Pop;
int town_B_Growth;
int years = 0;
change to
double town_A_Pop;
double town_A_Growth;
double town_B_Pop;
double town_B_Growth;
double years;
This should be ok. Because if using int to do division it not able return decimal number.
Like:
int tmp = 1;
int division = tmp / 5; //This result will return 0 , not return 0.2

C++ program doesn't output when I run on cmd or VScode (but on repl.it it does)

I have this C++ program I wrote that sums vectors:
#include <cmath>
#include <iostream>
using namespace std;
const float half_Pi = acos(0.0);
double *vectorSum(double *lengths, double *angels, int size, bool cartazian) {
double Cx, Cy, *res;
for (int i = 0; i < size; i++) {
Cx += cos(angels[i] / 90 * half_Pi) * lengths[i];
Cy += sin(angels[i] / 90 * half_Pi) * lengths[i];
}
if (cartazian) {
res[0] = Cx;
res[1] = Cy;
} else {
res[0] = sqrt(Cx * Cx + Cy * Cy);
res[1] = atan(Cy / Cx) * 90 / half_Pi;
}
return res;
}
int main() {
int numVectors, i = 0, carta;
bool cartazian;
cout << "enter number of vectors to sum: ";
cin >> numVectors;
double *lengths = new double[numVectors];
double *angels = new double[numVectors];
while (i < numVectors) {
cout << "enter length " << i + 1 << ": ";
cin >> lengths[i];
cout << "enter angel " << i + 1 << ": ";
cin >> angels[i];
i++;
}
cout << "would you like the sum presented in x and y? enter 1 for yes and 0 "
"for no: ";
cin >> carta;
if (carta == 0)
cartazian = false;
else if (carta == 1)
cartazian = true;
else
throw("must enter either 0 or 1");
double *totalVector = vectorSum(lengths, angels, numVectors, cartazian);
if (cartazian)
cout << "Vx = " << totalVector[0] << endl
<< "Vy = " << totalVector[1] << endl;
else
cout << "length = " << totalVector[0] << endl
<< "angle = " << totalVector[1] << "\u00B0" << endl;
return 0;
}
I've been able to run it completely fine on repl.it but when I try to run it on VScode (with minGW) or cmd it runs fine until I'm done with the input (doesn't show the result). Why doesn't it show the result? Is it because the throw (tried without and still not)? I don't think it's because the math functions because I ran them fine on another test file. How do I fix this?
The function vectorSum has undefined behavior due to the uninitialized pointer res which you are assigning data to as if it points to valid memory.
Note that you also have undefined behavior because you don't initialize the values Cx and Cy, but then start adding to them.
A naive fix for the first issue would be to allocate memory and then make the caller responsible for freeing it, or use smart pointers or a std::vector<double>, but really all you need is something like std::pair<double, double> instead. As for the second issue, it's as simple as initializing your values to zero.
Note that std::pair is defined in <utility> so you will need to include that.
std::pair<double, double> vectorSum(double *lengths, double *angels, int size, bool cartazian)
{
std::pair<double, double> res;
double Cx = 0, Cy = 0;
for (int i = 0; i < size; i++) {
Cx += cos(angels[i] / 90 * half_Pi) * lengths[i];
Cy += sin(angels[i] / 90 * half_Pi) * lengths[i];
}
if (cartazian) {
res.first = Cx;
res.second = Cy;
} else {
res.first = sqrt(Cx * Cx + Cy * Cy);
res.second = atan(Cy / Cx) * 90 / half_Pi;
}
return res;
}
The call:
std::pair<double, double> totalVector = vectorSum(lengths, angels, numVectors, cartazian);
if (cartazian)
cout << "Vx = " << totalVector.first << endl
<< "Vy = " << totalVector.second << endl;
else
cout << "length = " << totalVector.first << endl
<< "angle = " << totalVector.second << "\u00B0" << endl;
One last point is to take care of spelling things correctly in code. For instance, the correct spellings are:
angles
cartesian

My function factoring program has problems with variables, shows incorrect answers

I'm making a program that factors functions (f(x), not fully factored though):
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int x3;
int x2;
int x;
int remain;
int r = 0;
int factor;
int main() {
int b, i, j = 0;
int factors[101];
cout << "f(x) = x^3 + x^2 + x + r (Factor tool)" << endl;
cout << "x^3?: ";
cin >> x3;
cout << "x^2: ";
cin >> x2;
cout << "x: ";
cin >> x;
printf("remain (Y intercept): ");
scanf("%d", &b);
cout << "f(x) = " << x3 << "x^3 + " << x2 << "x^2 + " << x << "x + " << b
<< "" << endl;
cout << "factors of remainder are: " << endl;
for (i = 1; i <= b; i++) {
if (b % i == 0) {
factors[j++] = i;
printf("%d\t", i);
}
}
getchar();
while (true) {
int good;
if (factors[1] == 0) {
cout <<endl;
cout << "Equation Cannot be factored";
break;
}
int factorv = factors[r];
int nx1 = x3 * factors[r];
int nx2 = (nx1 + x2);
int nx3 = x + (nx2 * factors[r]);
int nx4 = remain + (nx3 * factors[r]);
if (nx4 == 0) {
int factored = (0 - factors[r]);
cout <<endl;
cout << "The Factored Function: f(x) = "
<< "(x " << factored << ")(" << nx1 << "x^3 + " << nx2 << "x^2 + "
<< nx3 << "x"
<< ")"
<< "";
break;
} else {
r = r + 1;
}
}
}
but in this part of the code, it shows as (x 0)(0x^3 + (x3 input instead of calculated nx1)x^2 + (x2 input instead of calculated nx2)x).
if (nx4 == 0) {
int factored = (0-factors[r]);
cout<<"The Factored Function: f(x) = "<<"(x "<<factored<<")("<<nx1<<"x^3 + "<<nx2<<"x^2 + "<<nx3<<"x"<<")"<<"";
break;
What happen to my nx variables? Why is it coming up incorrect or as a 0 when it was calculated properly above?
You have some of your variables twice:
int nx1;
int nx2;
int nx3;
int nx4;
They exists as global variables and again in the scope of main. They have the same name but are different variables.
Take the lesson: Global variables are no good.
Moreover you have a logic error in your code. When I add a std::cout << r << std::endl; in the last while loop I see its value increasing until there is a segfault, because factors[r] is out-of-bounds. broken code # wandbox
I cannot really tell you how to fix it, because I would have to dive into the maths first. I can only suggest you to never use infinte loops in numerical codes without an "emergency exit". What i mean is that unless fully tested, you cannot be sure that the loop will end at some point and when it doesn't typically the consequences are bad and difficult to diagnose. Always make sure the loop will end at some point:
int max_iteratons = 100;
int counter;
while (counter < max_iteratons) {
// do something
++counter;
}
if (counter == max_iterations) std::cout << "i have a bug :(";

whatever i use as inputs, outputs are all zeros

This is a question i am working on:
Prompt the user to enter five numbers, being five people's weights. Store the numbers in a vector of doubles. Output the vector's numbers on one line, each number followed by one space.
Also output the total weight, by summing the vector's elements.
Also output the average of the vector's elements.
Also output the max vector element.
So far this is the code i have
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
int maxWeight = 0;
int temp = 0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": ";
cout << inputWeights[i]<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++) {
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
When i run this code, whatever inputs i use(for the cin>>(...)), i get all zero's as output and i do not know why. can i get some help please.
update
cleaned up the code a little by getting rid of the cout<< inputWeights[i]<< endl;
and by adjusting vector inputWeights; at the beginning of the program.But the outputs are still not exactly what they are supposed to be. Instead, only the first 2 inputted values make it as outputs. Any reason why? thanks
update this is the right or correct code. Hope it helps someone in future.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector <float> inputWeights;
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
float maxWeight = 0.0;
float temp = 0.0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": "<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++){
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
You're making a vector of size 5:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
// == 0, 0, 0, 0, 0
Then, in your input loop, you're adding new values to the end:
inputWeights.push_back (42);
// == 0, 0, 0, 0, 0, 42
Then you're outputting the first five elements which were always zero.
You need to choose one thing or the other: either set the size of the vector at the start of the program, or grow the vector with push_back for as long as there's input. Both are valid options.
You can clean up your code and fix the problems by adopting modern C++ (as in, C++11 and later) idiom. You don't need to fill your code with for(int i = 0; i < something; i++) any more. There's a simpler way.
// Size fixed in advance:
vector<float> weights(NUM_WEIGHTS);
for (auto& weight : weights) { // note it's `auto&`
cout << "\nEnter next weight: ";
cin >> weight; // if it was plain `auto` you'd overwrite a copy of an element of `weight`
}
// Size decided by input:
vector<float> weights; // starts empty this time
cout << "Enter weights. Enter negative value to stop." << endl;
float in;
while (cin >> in) {
if(in < 0) {
break;
}
weights.push_back(in);
}
In either case, you can then play with the filled vector using another range-based for:
cout << "You entered: ";
for (const auto& weight : weights) {
cout << weight << " ";
}
You'll also need to remove the cout << inputWeights[i] << endl; line from your input loop if you resize the vector during input - as written you'd be reading elements which don't exist yet, and will probably get an array-index-out-of-bounds exception.
When you create define your inputWeights you are putting 5 items into it with default values.
vector<float> inputWeights(NEW_WEIGHT);
Change it to be just
vector<float> inputWeights;
And get rid of this line in your code or comment it out
cout << inputWeights[i]<< endl;
This is what you are looking for from the requirements of your program.
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
unsigned i = 0;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " ";
}
std::cout << std::endl;
double totalWeight = 0.0;
std::cout << "The total of all weights is: ";
for ( i = 0; i < weights.size(); ++i ) {
totalWeight += weights[i];
}
std::cout << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: ";
double max = weights[0];
for ( i = 0; i < weights.size(); ++i ) {
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << max << std::endl;
return 0;
}
The culprit to your problem for seeing all 0s as output is coming from these two lines of code:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
which is the same as doing this:
vector<float> inputWeights{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
you are then looping through up to 5 elements using NEW_WEIGHT when it would be easier to use inputWeights.size() when traversing through containers.
Edit - Condensed Version
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
unsigned i = 0;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
double totalWeight = 0.0;
double max = weights[0];
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " "; // Print Each Weight
totalWeight += weights[i]; // Sum The Weights
// Look For Max Weight
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << std::endl;
std::cout << "The total of all weights is: " << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: " << max << std::endl;
return 0;
}

Search a 3d Array

I need help with inputting a search array. I tried putting a binary search but I can't get it to work. everything else works up until I put the value I am searching for in the array, then it just crashes.
How it suppose to work:
input 2 coordinates with a value each
then it calculates the distance between them
then it suppose to let user search the coordinates for a value and state if found which coordinate it is at.
Thanks
#include "stdafx.h"
#include <iostream>
#include <iomanip> //for setprecision
#include <math.h>
#include <cstdbool>
#include <cstdlib> // Needed for rand and srand
#include <ctime> // Needed for the time function
using namespace std;
//Function Prototypes
void processThroughArray(int[][10][10], int, int, int, int, int, int);
int searchArray(int[][10][10], int, int, int, int, int, int, int, int);
const int SIZE = 10;
int main()
{
// establish array and set all values to 0
int myArray[10][10][10] = { 0 };
// establish x and y position markers
int x = 0;
int y = 0;
int z = 0;
int x2 = 0;
int y2 = 0;
int z2 = 0;
// establish input for x and y from the user
int xInput = 0;
int yInput = 0;
int zInput = 0;
int xInput2 = 0;
int yInput2 = 0;
int zInput2 = 0;
// variable for value entered
int inputValue = 0;
int inputValue2 = 0;
double distance = 0;
int searchValue;
int result;
// Get the user's value and coordinate
cout << "\nPlease enter the x coordinate ";
cin >> xInput;
cout << "\nPlease enter the y coordinate ";
cin >> yInput;
cout << "\nPlease enter the z coordinate ";
cin >> zInput;
cout << "\nPlease enter the value to place in " << xInput << "," << yInput << "," << zInput << " ";
cin >> inputValue;
// Get the user's ending value and coordinate
cout << "\nPlease enter the ending x coordinate ";
cin >> xInput2;
cout << "\nPlease enter the ending y coordinate ";
cin >> yInput2;
cout << "\nPlease enter the ending z coordinate ";
cin >> zInput2;
cout << "\nPlease enter the value to place in " << xInput2 << "," << yInput2 << "," << zInput2 << " ";
cin >> inputValue2;
// place the value in the coordinate
myArray[xInput][yInput][zInput] = inputValue;
cout << "\nYou have successfully placed the value " << inputValue << " in coordinate " << xInput << ", " << yInput << ", " << zInput << " ";
myArray[xInput2][yInput2][zInput2] = inputValue2;
cout << "\nYou have successfully placed the value " << inputValue2 << " in coordinate " << xInput2 << ", " << yInput2 << ", " << zInput2 << " ";
//Function performing for loop
processThroughArray(myArray, x, y, z, x2, y2, z2);
//calculate distance between the two coordinates
distance = sqrt(pow(xInput2 - xInput, 2.0) + pow(yInput2 - yInput, 2.0) + pow(zInput2 - zInput, 2.0));
cout << "\nThe distance between " << xInput << "," << yInput << "," << zInput << " and " << xInput2 << "," << yInput2 << "," << zInput2 << " is ";
cout << setprecision(4) << distance << endl;
// indicate end of array processing
cout << "\nArray Processed" << endl;
//User inputs value to search for
cout << "Enter the value you wish to look for: ";
cin >> searchValue;
result = searchArray(myArray, SIZE, searchValue, x, y, z, x2, y2,z2);
//If results contains a -1 the value not found
if (result == -1 )
{
cout << "That number does not exists in the array.\n";
}
else
{
cout << "\nValue " << searchValue;
cout << " is located at position: " << result << endl;
}
system("pause");
return 0;
}
//**************************************************************************
// Definition of function processThroughArray: Process through the array *
//the for loop *
//**************************************************************************
void processThroughArray(int myArray[][10][10], int x, int y, int z, int x2, int y2, int z2)
{
for (int x = 0, x2 = 0; x<10, x2 < 10; x++, x2++)
{
for (int y = 0, y2 = 0; y<10, y2 < 10; y++, y2++)
{
for (int z = 0, z2 = 0; z< 10, z2 < 10; z++, z2++)
{
// Display the value of the coordinate
cout << "\nCordinate " << x << ", " << y << ", " << z << " value is " << myArray[x, x2][y, y2][z, z2];
}
}
}
}
//**************************************************************************
// Definition of function searchArray: search array for the value input *
// *
//**************************************************************************
int searchArray(int myArray[][10][10], int size, int value,int x, int y, int z, int x2, int y2, int z2)
{
int index = 0;
int position = -1;
bool found = false;
while (index < size && !found)
{
if (myArray[index][index][index] == value)
{
found = true;
position = index;
}
index++;
}
return position;
}
You're defining SIZE as 1000, and you're passing it to searchArray():
const int SIZE = 1000;
// ...
searchArray(myArray, SIZE, searchValue);
You are doing the following in searchArray():
int searchArray(int myArray[][10][10], int size, int value)
{
int first = 0,
last = size - 1,
Since size is 1000, you are setting "first" to 0 and "last" to 999.
Then, you're doing the following (leaving out some irrelevant stuff):
middle = (first + last) / 2;
if (myArray[middle][middle][middle] = value)
So, let's take out a piece of paper, and a pencil. Since "first" is 0, and "last" is 999, this sets "middle" to 449.
So, we have two problems here:
1) You're assigning using the "=" operator, instead of comparing using "==", which appears to be your intent.
2) You are assigning a value to myArray[449][449][449]. Unfortunately, your array is much, much smaller:
int myArray[10][10][10] = { 0 };
Trying to access the 449th's element of the 449th array of ten elements, of the 449th array of ten arrays of ten elements, is not going to work very well. Even if you were comparing, or assigning something, either way this is undefined behavior, and an almost guaranteed crash.