Operations with structures, code not working? - c++

Assume you are given three variables, revenue, expenses, and profit, all of type Money (a structured type with two int fields, dollars and cents). Assign to profit the result of subtracting expenses from revenue. Let's make the happy assumption that revenue exceeds expenses. However you still may find that the cents part of expenses exceeds that of revenue. If that is the case you will have to "borrow" 1 from revenue dollars (i.e. subtract 1) and "give" it to revenue's cents (i.e. add 100!) in order to carry out the subtraction properly.
Here is what I have but it's not working:
if (revenue.cents < expenses.cents)
{
revenue.dollars = revenue.dollars -1;
revenue.cents = revenue.cents + 100;
profit = revenue - expenses;
}
else
{
profit = revenue - expenses;
}
I get this error message:
error: no match for 'operator-' in 'revenue - expenses'
Any help is appreciated. Thanks.

You're getting that error because you cannot subtract one structure from another. You will have to define an operator-() function for your struct.

You need to call each element of the structure and subtract them separately. MyProgLab will not allow you to define a function for this exercise. Not only that but if you enter the code that you have above it will tell you that 'you were not supposed to modify the element'. In order to avoid this you must conduct the borrowing of the dollar inside the arithmetic.
Like this:
if(expenses.cents > revenue.cents)
{
profit.dollars = (revenue.dollars - 1) - expenses.dollars;
profit.cents = (revenue.cents + 100) - expenses.cents;
}//end if

Related

Transforming a logic constraint into python pulp code

I started working on a problem in the past several days...
A company plans its business in a three month period. It can produce
110 units at a cost of 600 each. The minimum amount it must produce
per month is 15 units if active (but of course, it can choose to be closed
during the month, and produce 0 units). Each month it can subcotract the
prodution of 60 units, at a cost of 660 each. Storing a unit for one month
costs 20$ per unit per month. The marketing department has forcasted
sales of 100, 130 and 150 units for the next three months, respectively.
The goal is to meet the demand each month while minimizing the total
cost.
I deduced that we need to have an objective function of form min[Sum(i=0..3) 600*x1+660*x2+20*x3].
We need to add some constrains on x1>=15, and on x2 0<=x2<=60
Also we will also need another constraint for each month...
For the first one i=1 => x1+x2 = 100 - x3last (x3last is an extra variable that should hold the amount existing in deposit from the previous month), and for i=2 and i=3 same constraints.
I don't have any idea how to write this in pulp, and i would appreciate some help. Thx ^_^
I'd tend to agree with #Erwin that you should focus on formulating the problem as a Linear Program. It is then easy to translate this into code in PULP or one of many other PULP libraries/tools/languages.
As an example of this - lets work through this process for the example problem you have written out in your question.
Decision Variables
The first thing to decide is what you can/should decide. This set of information is called the decision variables. Picking the best/easiest decision variables for your problem comes with practice - the important thing is that once you know the values of the variables you have a unique solution to the problem.
Here I would suggest the following. These assume that the forecasts for demand are perfect. For each month i:
Whether the production line should be open - o[i]
How much to produce in that month - p[i]
How much to hold in storage for next month - s[i]
How much to get made externally - e[i]
Objective Function
The objective in your case is obvious - minimise the total cost. So we can just write this down: sum(i=0...2)[p[i]*600 + s[i]*20 + e[i]*660]
Constraints
Let's lift these directly our of your problem description:
"It can produce 110 units at a cost of 600 each. The minimum amount it must produce per month is 15 units if active (but of course, it can choose to be closed during the month, and produce 0 units)."
p[i] >= o[i]*15
p[i] <= o[i]*110
The first constraint forces the minimum production about to be 15 if the production is open that month (o[i] == 1), if the production is not open this constraint has not effect. The second constraint sets a maximum value on p[i] of 110 if the production is open and a maximum production of 0 if the production is closed that month (o[i] == 0).
"Each month it can subcotract the prodution of 60 units, at a cost of 660 each"
e[i] <= 60
"The marketing department has forcasted sales of 100, 130 and 150 units for the next three months, respectively. The goal is to meet the demand each month while minimizing the total cost." If we declare the sales in each mongth to be sales[i], we can define our "flow constraint" as:
p[i] + e[i] + s[i-1] == s[i] + sales[i]
The way to think of this constraint is inputs on the left, and outputs on the right. Inputs of units are production, external production, and stuff taken out of storage from last month. Outputs are units left/put in storage for next month and sales.
Finally in code:
from pulp import *
all_i = [1,2,3]
all_i_with_0 = [0,1,2,3]
sales = {1:100, 2:130, 3:150}
o = LpVariable.dicts('open', all_i, cat='Binary')
p =LpVariable.dicts('production', all_i, cat='Linear')
s =LpVariable.dicts('stored', all_i_with_0, lowBound=0, cat='Linear')
e =LpVariable.dicts('external', all_i, lowBound=0, cat='Linear')
prob = LpProblem("MinCost", LpMinimize)
prob += lpSum([p[i]*600 + s[i]*20 + e[i]*660 for i in all_i]) # Objective
for i in all_i:
prob += p[i] >= o[i]*15
prob += p[i] <= o[i]*110
prob += e[i] <= 60
prob += p[i] + e[i] + s[i-1] == sales[i] + s[i]
prob += s[0] == 0 # No stock inherited from previous monts
prob.solve()
# The status of the solution
print ("Status:", LpStatus [prob.status])
# Dislay the optimums of each var
for v in prob.variables ():
print (v.name, "=", v.varValue)
# Objective fcn
print ("Obj. Fcn: ", value(prob.objective))
Which returns:
Status: Optimal
external_1 = 0.0
external_2 = 10.0
external_3 = 40.0
open_1 = 1.0
open_2 = 1.0
open_3 = 1.0
production_1 = 110.0
production_2 = 110.0
production_3 = 110.0
stored_0 = 0.0
stored_1 = 10.0
stored_2 = 0.0
stored_3 = 0.0
Obj. Fcn: 231200.0

How to calculate the same accumulated amount

im trying a code to calculate accumulated/incremented amount of specific value.
for (int a=1; a<= qtydrink; a++)
{
cout << "enter drink name:"
cin.getline( drink, 15)
.......
if (strcmp(drink, "beer") == 0)
{
payment = 10.00;
.......
oke so one beer would cost 10$, but if the user input another beer, will it add or replace or something? i have an amount of 1.20 and user inputs it twice, amounting to 2.40 but in the output its just 2.20 sometimes.
i have 2 for loops. one for food and one for drinks. each time user can input different types of foods or drinks with different payments. i have to total up both food and drink's payment in the end plus tax.
please elaborate.
On the assumption that you are using payment as your output, that would be because you are setting the payment to be equal to 10.00, rather than incrementing it. To perform the increment, use += instead of =
EDIT: Everything you need to know about operators can be found here

multiple conditions on multiple variables

would really love to get some help on a sas program i am trying to write
I have five variables that have the options Interest or Rewards
call them wo1 wo2 wo3 wo4 wo5
is there a way to do an if statement that checks all five for the value of "Interest" and then produces a calcualted variable with the totals of the variable that holds the amount value which are wo1amt wo2amt wo3mt etc.
and the ones that do not have the value of interest return a value of 0.
or would i need to do an if statement for each, creating a calc var for each and then summing them all together with another ??
any assistance, direction would be very appreciated...
If I'm understanding correctly, it looks like you will need multiple if statements.
You could initialize a total variable, and then add to it for each contributing variable, like this:
total = 0;
if wo1 = 'Interest' then total = total + wo1amt;
if wo2 = 'Interest' then total = total + wo2amt;
if wo3 = 'Interest' then total = total + wo3amt;
if wo4 = 'Interest' then total = total + wo4amt;
if wo5 = 'Interest' then total = total + wo5amt;
Arrays work nicely for situations like this.
array wo(*) wo1-wo5;
array woamt(*) wo1amt wo2amt wo3amt wo4amt wo5amt;
total = 0;
do i = 1 to 5;
total + woamt(i)*(wo(i)='Interest');
end;

Invalid Syntax attempting to write Python closure

I am attempting to write a function (in Python 2.7) which takes an outstanding balance and annual interest rate then returns the min monthly payment to the nearest cent using bisection search to solve problem #3. I am trying to follow DRY principles by writing a function inside the main function which should return a list with the balance after a year and the number of months (the loop should break if balance hits zero or less) which will need to be calculated twice in my main function. As I try to test this initial closure before moving on I am getting a syntax error on the line assigning monthlyPayment. What am I doing wrong?
# Problem Set 1("C")
# Time Spent: xx hours
def payInOne_BisectionSearch (balance,annualRate):
#initialize variables
initialBalance = balance
monthlyRate = annualRate/12
minMonthly = balance/12
maxMonthly = (balance * (1 + monthlyRate ** 12 )/12
monthlyPayment = (minMonthly + maxMonthly)/2
numMonths = 1
#define function to check balance after 12 months
def balanceAfterYear (balance, monthlyRate, monthlyPayment):
for numMonths in range (1,13):
interest = balance * monthlyRate
balance += interest - monthlyPayment
if balance <= 0:
break
return [balance, numMonths]
resultList = balanceAfterYear(initialBalance, monthlyRate, monthlyPayment)
print resultList[0],resultList[1]
payInOne_BisectionSearch (input("Enter the outstanding balance"),input("Enter annual rate as a decimal"))
You forgot a closing bracket in the previous line.
maxMonthly = (balance * (1 + monthlyRate ** 12 )/12

a lot of decimal value storage in C++

I wanted to write a program that returns how many months we could survive when we're given
our monthly expenditure, amount of disposable income, and interest rate (all in integers).
For instance, if we start with disposable income = 1000, interest rate = 5%, monthly expenditure = 100, then
after first month: 1000*1.05 - 100 = 950, we have 950 dollars left
after second month: = 950*1.05 - 100 = 897.5
and so on, and in the end, we can survive 14 months.
I wrote the following code in C++:
int main(){
int i=0;
int initialValue;
int interest;
int monthly;
double value=1.0*initialValue;
double r=1+1.0*interest/100;
while(value > 0){
if(value < monthly){
break;
}
else
{
value=value*r-monthly;
i++;
}
};
cout<<i;
return 0;
}
but for sufficiently large values of initialValue and small values of monthly, the program I wrote runs very slowly to the degree that it's unusable. Is there a problem with the code that makes it run not well (or very slow)?
Any help would be greatly appreciated.
double cannot store numbers precisely. One consequence of this is when you subtract a very small number from a very large number, the result is not changed from the original large value.
One solution to this problem is to use an int to do your calculations. Think of the values as the number of pennies, rather than the number of dollars.
A few notes:
The *1.0's are pointless. Instead, take advantage of implicit and explicit casts:
double value=initialValue;
double r=1+(double)interest/100;
++i is faster than i++.
value=value* can be rewritten as value*=.
You can mix the first two conditionals. Remove the if...break and change the while loop to while (value > 0 && value < monthly).
On the face of it, the reason this runs slowly is the large number of iterations. However, you didn't specify any specific numbers and I would expect this code to be able to execute at least a million iterations per second on any reasonably fast processor. Did you really expect to need to calculate more than 1 million months?
Apart from the novice style of the code, the underlying problem is the algorithm. There are very simple formulae for making these calculations, which you can find here: https://en.wikipedia.org/wiki/Compound_interest. Your situation is akin to paying off a loan, where running out of money equals loan paid off.