How to perform mathematical operations? - c++

I have been given the following assignment and am unsure how to implement it:
Calculate the fee for a taxi ride. The formula is as follows:
The first kilometer costs 50. Each extra 200m costs 5. If the distance
is more than 30km then each extra kilometer adds 10 to the fee. The
program has to input the total distance (in km) and calculate the
charge.
I wrote the following code but don't know what to do with "200m costs 5" part...
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
double totalfee, km, m;
cout << "distance" << endl;
cin >> km;
m = km * 1000;
if (km < 30)
{
totalfee = 50;
cout << "totalfee = " << totalfee << endl;
}
else if (km > 30)
{
totalfee = 60;
cout << "totalfee = " << totalfee << endl;
}
system("pause");
}
it is in c++

Firstly, the question contains some ambiguities - we know that the first km costs 50, and any 200m above the first km adds an additional 5. However, if the distance is greater than 30km, is the 10 per km fee additional on top of the 5, or does it replace the 5? Additionally, should partial amounts count e.g. is 5 charged if the total distance is 1100m? I'll assume that a partial amount does not count.
Secondly, you have some logic errors in your code. This block:
if (km < 30)
{
totalfee = 50;
cout << "totalfee = " << totalfee << endl;
}
Ignores the extra 5s that you should be charging above the first 1km.
The next block:
else if (km > 30)
{
totalfee = 60;
cout << "totalfee = " << totalfee << endl;
}
Contains the same logic error as the first, but also ignores the extra 10 to charge for each km, only charging this once (and charging it when it shouldn't at all, e.g. if the total km is 30.5).
You could try something like this:
//Assuming the two fees are both added separately from one another:
totalfee = 50; // Charge at least this much no matter what
// Pseudo-code:
if (km > 1)
{
// Subtract 1 from km
// Divide result by 0.2, discard any remainder
// Multiply result by 5, and add the total to totalfee
}
if (km > 30)
{
// Subtract 30 from km
// Divide result by 1, discard any remainder
// Multiply result by 10, and add the total to totalfee
}
cout << "totalfee = " << totalfee << endl;

Related

Don't understand why output is incorrect

I'm currently doing a Zybooks lesson for my C++ class and we're going over while loops. In this question, it wants me to calculate how many years it takes for a bank account to double it's initial balance. There is also an annual contribution added. My code is as follows:
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest + contribution;
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
I used this as an answer but was met with this unexpected result:
Output differs. See highlights below.
Input
100
Your output
Annual contribution:
Year: 13
Balance: 20627.8
Expected output
Annual contribution:
Year: 13
Balance: 20527.8
I see the expected output and your output differs by a 100, i.e. your contribution. Maybe the evaluation system doesn't add annual contribution once your target is reached. The below code gets your required output, but I think your code should have been the correct answer.
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
The problem is that you're making a contribution after the 13th year even though the target has been reached.
I would restructure to something like this, in order to only check the condition once:
while (true)
{
year++;
double interest = balance * RATE / 100;
balance += interest;
if (balance >= TARGET)
{
break;
}
balance += contribution;
}
This is because the last time the loop is being executed (at year=13), balance is less than TARGET but, after adding a contribution and interest into it, it jumps out of the loop with contribution and interest added to it.
So, the solution can be to use an if statement within the while loop to check if it exceeds the TARGET; if it does, then don't add contribution into it.
Replace your while loop with the following:
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}

Including Missing Data in a C++ Array

I am new to C++.
Below is code that lets a user enter five elements into an array, then sums those values, and obtains the mean and a predicted future value.
The code works fine if the user enters five elements, but how do I handle the situation in which one or more values are missing?
I have written code further below that seems to solve this problem, by defining a missing value to be a negative number. That code also seems to work fine. But, is there a better, accepted way of handling missing values in a C++ array?
If I try to run the first code in Microsoft Visual Studio 2019, I do not even know what to enter for a missing value. If I do not enter anything, and just press the Enter key, nothing happens.
Here is the original code that works with five elements. This code is slightly modified from code written by Saldina Nurak:
#include <iostream>
using namespace std;
int nmonths = 6;
int totalmonths = 24;
int main()
{
// {100, 220, 300, 0, 200, 250}
// This line works in the command window
// float monthArray[nmonths];
// for Microsoft Visual Studio 2019
float monthArray[6];
float total = 0;
for(int i = 0; i <= (nmonths-1); i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> monthArray[i];
total += monthArray[i];
}
float average = total / nmonths;
float inTwoYears = average * totalmonths;
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
Enter Amount 1: 100
Enter Amount 2: 220
Enter Amount 3: 300
Enter Amount 4: 0
Enter Amount 5: 200
Enter Amount 6: 250
total = 1070
average = 178.333
inTwoYears = 4280
Here is the modified code I wrote that seems to handle missing values, by defining them to be negative numbers:
#include <iostream>
using namespace std;
int nmonths = 6;
int totalmonths = 24;
int emptycounter = 0;
int main()
{
// This works from the command window
// float monthArray[nmonths]; // {100, 220, 300, 0, -99, 250};
// for Microsoft Visual Studio I have to use
float monthArray[6];
float total = 0;
for(int i = 0; i <= (nmonths-1); i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> monthArray[i];
if (monthArray[i] >= 0) emptycounter++;
else (emptycounter = emptycounter);
if (monthArray[i] >= 0) total += monthArray[i];
else total = total;
}
float average = total / emptycounter;
float inTwoYears = average * (totalmonths - (nmonths - emptycounter));
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
C:\Users\mark_>cd C:\Users\mark_\myCppprograms
C:\Users\mark_\myCppprograms>c++ MissingDataInArray2.cpp -o MissingDataInArray2.exe -std=gnu++11
C:\Users\mark_\myCppprograms>MissingDataInArray2
Enter Amount 1: 100
Enter Amount 2: 220
Enter Amount 3: 300
Enter Amount 4: 0
Enter Amount 5: -99
Enter Amount 6: 250
total = 870
average = 174
inTwoYears = 4002
What is the standard approach for dealing with missing values in C++ and how does a user enter a missing value from the keyboard?
You would have to define what is supposed to be a missing value if you are trying to read as a number. You could maybe read the line and try to parse it to a int and if unable to parse then it would be your missing value?
Also, you are not using C++ arrays, you are using C arrays.
C++ has an array container but vector gives you much more flexibility.
You could do something like this:
vector<int> monthArray;
int value;
for(int i = 0; i < nmonths; i++) // See the change done in the test
{
cin >> value;
if(value > 0)
monthArray.push_back(value); // This would insert at the end and take care of resizing the container as needed.
}
monthArray.size(); // This returns how many elements you have in the container
Both your else clauses are assigning a variable to itself. You can erase both and put the 2 statements inside the same if:
if (monthArray[i] >= 0)
{
emptycounter++;
total += monthArray[i];
}
But if you use vector you won't need emptycounter. The size of the vector will contain the number of valid elements.
for(int i = 0; i < nmonths; i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> value;
if(value > 0)
{
monthArray.push_back(value);
total += value;
}
}
After all that... There is this question: Do you really need an array? You just seem to accumulate the valid values and never refer to the array after saving the elements on it.
P.S: to use vector you need to #include<vector>
What is the standard approach for dealing with missing values in C++ ?
std::optional is standard and serves the need.
How does a user enter a missing value from the keyboard?
There is no definition of operator>> for istream and std::optional<float> but you can write a function that behaves the way you want.
For example you could use std::getline to always read an entire line, then if the line is blank return an empty std::optional<float> and if not then parse the number and return a std::optional<float> that contains it.
Here is code that implements the answer from #vmp when missing observations are defined as NA (as in R and suggested by #Yksisarvinen in a comment) by using stoi. I have not yet figured out how to implement the answer from #Ben Voigt.
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int nmonths = 6 ;
int totalmonths = 24 ;
int main()
{
float total = 0;
vector<int> monthArray;
string value;
for(int i = 0; i < nmonths; i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> value;
if(value != "NA")
{
monthArray.push_back(stoi(value));
total += stoi(value);
}
}
float average = total / monthArray.size() ;
float inTwoYears = average * (totalmonths - (nmonths - monthArray.size())) ;
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
// C:\Users\mark_>cd C:\Users\mark_\myCppprograms
// C:\Users\mark_\myCppprograms>c++ vector2.cpp -o vector2.exe -std=gnu++11
// C:\Users\mark_\myCppprograms>vector2
// Enter Amount 1: 100
// Enter Amount 2: 220
// Enter Amount 3: 300
// Enter Amount 4: 0
// Enter Amount 5: NA
// Enter Amount 6: 250
// total = 870
// average = 174
// inTwoYears = 4002

C++ program on how much a person would earn over time if salary is one penny per day (Not an IT student)

I have a project to write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
This is my code so far and I can't seem to get it to work properly (not an
IT student)
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip.h>
int main()
{
int days;
double pennies = 0.01;
double total = 0.0;
double fixed;
double showpoint;
cout << "For how many days will the pay double?";
cin >> days;
cout << endl << "Day Total Pay\n";
cout << "------------------------\n";
for (int count = 1; count <= days; count++)
{
cout << count << "\t\t$\t" << (pow(2, pennies)) << endl;
}
cout << setprecision(2) << fixed << showpoint;
cout << "--------------------------------\n";
cout << "Total $\t" << total << endl;
getch();
return 0;
}
I've tried to explain the changes I have made, but if you need to know more please ask
// Headers for standard library features don't have .h on the end (normally)
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<iomanip>
int main()
{
int days = 0;
// double pennies = 0.01; Not needed.
double total = 0.0;
// If you don't initialise variables it will cause a crash or undefined behaviour.
// double fixed;
// double showpoint;
while (days < 1) // This prevents negative or 0 day contracts.
{
// You need to use the full name to cout or that abomination of a command using namespace std
std::cout << "For how many days will the pay double?";
std::cin >> days;
}
std::cout << std::endl << "Day Total Pay\n";
std::cout << "------------------------\n";
// looping from 0 while less than days is more "normal".
for (int count = 0; count < days; count++)
{
double payForTheDay = (pow(2, count));
std::cout << count << "\t\t$\t" << payForTheDay << std::endl;
total += payForTheDay; // You need to increment the total.
}
// Not sure what this is about
// std::cout << std::setprecision(2) << fixed << showpoint;
std::cout << "--------------------------------\n";
std::cout << "Total $\t" << total << std::endl;
getch();
return 0;
}
Try to replace (pow(2, pennies)) with (pennies * pow(2, (count - 1)))...
Notes:
Shouldn't pennies actually be named dollars?
To calculate the total, just increase it by the daily salary for each day (e.g. inside the loop where you output each table row).
So look at the basic of the problem. It is basically a geometric progression.
In a geometric progression sum of n numbers is;
Sn=a1((1-r^n)/(1-r))
[a1=first element(in your case 1);r=2(in this case)]
Use the formula to get number of pennies for n days.
Now convert it into dollar value.
If you need full code comment here.
Quite late, but using bitwise shift is the best thing for 2^n in my opinion. It's fast and easy to use.
int days; // = amount of days for payment;
// Add input/output logic
if (days<1) {
// Do invalid input logic
}
// Use long long if days>31
for (int K=0; K<days; K++)
cout<<"Day "<<K<<": "<<(1<<K)<<"\n;
Here 1<<K is 2^K
Alternatively, you can use a variable to save the payment
and shift it by 1 each iteration.

C++ cashier code

The question:
Giving change. Implement a program that directs a cashier how to give
change. The program has two inputs: the amount due and the amount
received from the customer. Display the dollars, quarters, dimes,
nickels, and pennies that the customer should receive in return.
What i have so far:
#include <iostream>
using namespace std;
int main()
{
double amount_due;
double amount_recieved;
cout << "Enter amount due: " << endl;
cin >> amount_due;
cout << "Enter amount received: ";
cin >> amount_recieved;
int change = amount_recieved - amount_due;
int dollar = 100;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
//Return change in full dollars
cout << "dollars: " << change % 100 << endl;
//Return change in quarters
cout << "quarters: " << (change % 100) % 25 << endl;
//Return change in dimes
cout << "dimes: " << ((change % 100) % 25) % 10 << endl;
// Return change in nickels
cout << "nickels: " << (((change % 100) % 25) % 10) % 5 << endl;
//Return change in pennies
cout << "pennies: " << ((((change % 100) % 25) % 10) % 5) % 1 << endl;
system("pause");
return 0;
}
I realize there are some other one of these answered but they may be to advanced to use in my code, what am i doing wrong?
What you want to do is the same as a cashier would do.
First ensure the change is represented as whole pennies.
Then provide enough dollars until the change remaining is less than a dollar. Then move on to quarters, then dimes, nickels and pennies.
So for the dollar case, pseudo-code would be:
dollars = change / 100 # get integral number of dollars
change = change % 100 # and reduce change-left-to-go accordingly
print dollars, " dollars"
It should then be a simple matter to apply that logic to the other coin types in order of reducing value.
There are several problems. The first is that you ask the user to input values, but don't specify what they are. If the user enters a number that's not in pennies, you're not going to get the value you expect. I expect this input should be in dollars. So, first, change change into:
change = int((amount_recieved - amount_due) * 100.0)
Next:
cout << "dollars: " << change % 100 << end;
Will return the remainder of dividing change by 100, which is not what you want. You simply want to divide dollars by 100. You also want to likely modify change to stop you having to repeat this math.
dollars = change / 100;
cout << "dollars: " << dollars << endl;
change -= dollars*100;
From there, the rest of the code should work as expected minus the % 100 parts. As others have mentioned in the comments to the question, your problem is arising from not thinking the math through first, not from doing anything inherently wrong with C++. This would have produced the wrong result in any language, including writing it down as math on a blackboard.
As others have mentioned, you are not doing the step required to get this working, and that is repeated subtraction. Yes, you subtracted the price from the amount given, and determined the dollars to give, but you failed to subtract out those dollars, giving you a new total to determine how many quarters.
Something like this (assuming you're working in pennies):
change_left = customer_payment - original_cost;
//...
number of dollars = change_left / 100;
change_left = change_left - (100 * number of dollars); <-- where is this?
Now how do you determine the number of quarters? You have a "running total" called change_left that is being reduced by the change you currently have given the customer. You repeat similar steps to get the number of quarters, then number of dimes, nickels, etc., i.e. divide by 25, then subtract out the number of quarters giving a new "change_left". Then repeat for 10 to get the dimes, 5 to get the number of nickels, etc.
So again, the problem isn't C++ -- the issue is that you are not thinking this out as a discrete series of steps that lead to a final goal.
#include <iostream>
using namespace std;
int main() {
double amount_due;
double amount_recieved;
cout << "Enter amount due: " << endl;
cin >> amount_due;
cout << "Enter amount received: ";
cin >> amount_recieved;
int change = amount_recieved - amount_due;
int dollar = 100;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
//Return change in full dollars
cout << "dollars: " << change / 100 << endl;
//Return change in quarters
cout << "quarters: " << (change % 100) / 25 << endl;
//Return change in dimes
cout << "dimes: " << ((change % 100) % 25) / 10 << endl;
// Return change in nickels
cout << "nickels: " << (((change % 100) % 25) % 10) / 5 << endl;
//Return change in pennies
cout << "pennies: " << ((((change % 100) % 25) % 10) % 5) / 1 << endl;
return 0;
}

How to break a for loop and convert integers?

My program needs to calculates the cost for customers
to replace their carpet at $5 per yard for installation, various padding options,
carpet cost and total all rounded up to the nearest yard.
Padding is cost is based on:
Good - $3 per yard - 1-3year warranty
Better - $4 per yard 3-5 year warranty
Best- $5 per yard - 5-10 year warranty
Excellent - $7 per yard 10-20 year warranty
Operation:
Prompt User for number of rooms For each room:
Prompt length than width for each number of room
Calculate square feet a. convert square feet to square yards and round up b. square yards = yards required for room c. Calculate installation cost by square yard *$5
Prompt user to choose padding. a. Multiply padding cost by square yard of room
Prompt user for carpeting cost per sq yard of room: a. Calculate cost by multiplying input by squareyards required
Output total yards required
Output Installation cost
Output padding cost
Output carpet cost
Output total cost = + Installation + PAdding + Carpet
Grand total = cost of each room
******************/
I have 5 problems so far:
How to convert the integer padding choice to the cost of the quality
The floor loop will not break between rooms
When it displays the room number it starts at 0
How do I get the dollars to display to 2 decimal places?
How will I get the total of each rooms to store as doubles to get the grand total?
#include <iostream>
#include <iomanip>
#include <string>
#include <conio.h>
#include <string>
using namespace std;
const float INSTALL_COST = 5;
const float GOOD_PAD = 3;
const float BETR_PAD = 4;
const float BEST_PAD = 5;
const float EXC_PAD = 7;
const double SQU_FT_YD = 9;
int main ()
{
int padding, rooms, numreq, squareYards;
double length, width, squareFeet,priceSquareYard;
double paddingCost, installFee, totalCost, carpetCost;
//step 1:
cout << "Enter number of rooms: ";
cin >> numreq;
cout << endl;
//Step 2
cout << "Enter length of room: ";
cin >> length;
cout << endl;
cout << "Enter width of room: ";
cin >> width;
cout << endl;
//step 3
cout << "Select quality of padding:<1-4> ";
cout << "\n1. Good - $3 per yard - 1-3 year warranty \n2. Better - $4 per yard 3-5 year warranty \n3. Best- $5 per yard - 5-10 year warranty \n4. Excellent - $7 per yard 10-20 year warranty: ";
cin >> padding;
cout << "Enter price of carpeting per square yard of room: ";
cin >> priceSquareYard;
//step3
for(int x = 0; x < numreq; x++)
{
squareFeet = length * width;
squareYards = ((squareFeet / SQU_FT_YD) + 0.5);
if (squareYards > 0)
squareYards++;
installFee = squareYards * INSTALL_COST;
carpetCost = priceSquareYard * squareYards;
paddingCost = squareYards * padding;
totalCost = carpetCost + installFee + paddingCost;
cout << "\n Room " << x << " Yards Required = " << squareYards;
cout << "\n Room " << x << " Installation = $" <<installFee;
cout << "\n Room " << x << " Padding Cost = $" << paddingCost;
cout << "\n Room " << x << " Carpet Cost = $" << carpetCost;
cout << "\n Room " << x << " Total Cost = $" << totalCost;
}
_getch();
return 0;
}
To get totals within loops, simply store a variable outside of the loop, start it at 0, and increment it within the loop whenever necessary.
And you can use break; to break out of the loop completely. Also, if you need this, continue; will let you stop the current iteration and jump straight to the next iteration of your for-loop.
And for number 4, check this out:
NumberFormat/DecimalFormat treats certain floating-point values as longs instead of doubles