Discount C++ program using a switch statement - c++

so basically im trying to do a small program that let the user enter a value then if the value equal or greater than x make discount something like 12%
here is an example
15% discount, if sales are greater than or equal to 1000
10% discount, if sales are greater than or equal to 500
5% discount, if sales are greater than or equal to 250
0, otherwise.
i know how to do it using if statement, but in switch i have no idea, there could be million cases about the entered value, so i need help if its possible
Thanks

One way would be
int sales; // ToDo - needs a value
double discount;
switch (std::max(sales / 250, 4)){
case 4:
discount = 0.15;
break;
case 3: case 2:
discount = 0.10;
break;
case 1:
discount = 0.05;
break;
default:
discount = 0.0;
}
but just because it's possible doesn't mean it's the right thing to do. It most certainly is not. My solution would be a pain in the neck to tweak if the thresholds change - that is poor program design indeed since you don't really want to have to change the program control flow if parameters change.
Use an if block, or some kind of data structure.

Related

Pinescript - Syntax error at input 'else'

I am having an issue with pinescript. Never used it before and havent coded in years so im very rusty.
I would love an opinion of why I am getting the error on line 21, which is the only 'else if' line in the block.
//#version=4
tradeDirection = input(direction.up, "Trade Direction") // direction of the breakout (up or down)
breakoutPeriod = input(14, "Breakout Period") // number of bars to look back for the breakout
stopLoss = input(0.002, "Stop Loss") // stop loss in percentage of the trade value
takeProfit = input(0.004, "Take Profit") // take profit in percentage of the trade value
maxTrades = input(2, "Maximum Number of Trades") // maximum number of trades to have open at the same time
maxRisk = input(0.01, "Maximum Risk per Trade") // maximum risk per trade in percentage of the account value
// Next, we create a variable to track the highest or lowest price in the breakout period
breakoutPrice = tradeDirection == direction.up ? highest(high, breakoutPeriod) : lowest(low, breakoutPeriod)
// Then, we check if the current price has broken out of the breakout period and if we have not reached the maximum number of open trades
if (tradeDirection == direction.up and close > breakoutPrice and strategy.opentrades < maxTrades)
// If it has, we calculate the trade size based on the maximum risk per trade
tradeSize = maxRisk / (stopLoss * close)
// And enter a long position with the calculated trade size
strategy.entry("Long", strategy.long, tradeSize)
else if (tradeDirection == direction.down and close < breakoutPrice and strategy.opentrades < maxTrades)
// If it has, we calculate the trade size based on the maximum risk per trade
tradeSize = maxRisk / (stopLoss * close)
// And enter a short position with the calculated trade size
strategy.entry("Short", strategy.short, tradeSize)
// Finally, we set our stop loss and take profit levels
strategy.exit("Stop Loss", "Long", stopLossType.percent, stopLoss)
strategy.exit("Take Profit", "Long", profitType.percent, takeProfit)
// We repeat the same process for the short position
strategy.exit("Stop Loss", "Short", stopLossType.percent, stopLoss)
strategy.exit("Take Profit", "Short", profitType.percent, takeProfit)
I've looked around at other versions to see if its just a version issue but nothing that gives me a reaosn why its erroring out.
I get the feeling its something before or within the else if statement.
I retyped your script so it would compile and have no warnings or errors. One problem was the indentation was missing on the if and else. Another problem was the direction.up variable was missing. It is not allowed to have a . in a variable name. Another problem was that strategy("breakout strat") was missing, so I added it. The logic in the code I typed is probably wrong, but there are no errors.
//#version=4
strategy("breakout strat")
tradeDirection = input(true, "Trade Direction") // direction of the breakout (up=true or down=false)
breakoutPeriod = input(14, "Breakout Period") // number of bars to look back for the breakout
stopLoss = input(0.002, "Stop Loss") // stop loss in percentage of the trade value
takeProfit = input(0.004, "Take Profit") // take profit in percentage of the trade value
maxTrades = input(2, "Maximum Number of Trades") // maximum number of trades to have open at the same time
maxRisk = input(0.01, "Maximum Risk per Trade") // maximum risk per trade in percentage of the account value
// Next, we create a variable to track the highest or lowest price in the breakout period
breakoutPrice = tradeDirection == true ? highest(high, breakoutPeriod) : lowest(low, breakoutPeriod)
// Then, we check if the current price has broken out of the breakout period and if we have not reached the maximum number of open trades
if (tradeDirection == true and close > breakoutPrice and strategy.opentrades < maxTrades)
// If it has, we calculate the trade size based on the maximum risk per trade
tradeSize = maxRisk / (stopLoss * close)
// And enter a long position with the calculated trade size
strategy.entry("Long", strategy.long, tradeSize)
else if (tradeDirection == false and close < breakoutPrice and strategy.opentrades < maxTrades)
// If it has, we calculate the trade size based on the maximum risk per trade
tradeSize = maxRisk / (stopLoss * close)
// And enter a short position with the calculated trade size
strategy.entry("Short", strategy.short, tradeSize)
// Finally, we set our stop loss and take profit levels
strategy.exit("Stop Loss", "Long", loss=stopLoss)
strategy.exit("Take Profit", "Long", loss=takeProfit)
// We repeat the same process for the short position
strategy.exit("Stop Loss", "Short", loss=stopLoss)
strategy.exit("Take Profit", "Short", loss=takeProfit)
Put an indentation on line 21 to get rid of this error :
if .....
----> First block
else if
----> Other block
In your code other indentations are missing, and other error are present (direction.up doesn't exist for example... but you should ask another question for another error)

How to loop a switch statement until desired number is found?

cout<<"========================================="<<endl<<endl;
cout<<"The amount you need to pay is RM "<<total<<endl;
cout<<"=========================================="<<endl<<endl;
cout<<"You can pay using ($0.10 [1] $0.20 [2] $0.50 [3] $1 [4] $5 [5] $10 [6] $20 [7] $50 [8] )"<<endl;
cin>>choice2;
switch(choice2){
case 1:
total = total - 0.10;
break;
case 2:
total = total - 0.20;
break;
case 3:
total = total - 0.50;
break;
case 4:
total = total - 1;
break;
case 5:
total = total - 5;
break;
case 6:
total = total - 10;
break;
case 7:
total = total - 20;
break;
case 8:
total = total - 50;
break;
default:
cout<<"inavalid!"<<endl;
}
if(total > 0){
cout<<"you still need to pay "<<total<<endl;
cin>>choice2;
}
Extra information: My total is $5
I am trying to let it loop until the total amount is paid, say I choose case 4 which is $1. It's suppose to let me insert the remaining amount I am supposed to pay, which is $4, but the program ends after I insert another switch case option.
This part, isn't it supposed to be looping until my total is 0?
if(total > 0){
cout<<"you still need to pay "<<total<<endl;
cin>>choice2;
}
Thanks in advance for any help, I am also happy to learn any shorter way of writing this program if there is any, also is there anyway I can implement array into this program?
No, neither the switch nor the if will cause your program to loop.
You're probably looking for something along the lines of
while(total > 0)
{
cin>>choice2;
switch(choice2){
// left out for clarity
}
if(total > 0){
cout<<"you still need to pay "<<total<<endl;
//Instead of getting the input in 2 different locations, just get it again at the start of the next loop.
}
}

Why is my code getting an infinite loop?

minimunpaymonth = 0
balance = 4773
annualInterestRate = 0.2
def function(minimunpaymonth):
global balance
month = 1
while month <= 12:
balance = balance - minimunpaymonth
anninterest = annualInterestRate/12 * balance
balance = balance + anninterest
month += 1
return balance
while function(minimunpaymonth) >= 0:
minimunpaymonth += 10
print "Lowest Payment: " + str(minimunpaymonth)
the second while loop is infinite and i dont know why. the first is ok because i have ran it
when the loop increases minimunpaymonth, value of balance goes down, so there will be a moment when balance is negative
def function(minimunpaymonth, balance, annualInterestRate):
month = 1
while month <= 12:
balance = balance - minimunpaymonth
anninterest = annualInterestRate/12 * balance
balance = balance + anninterest
month += 1
return balance
while function(minimunpaymonth, balance, annualInterestRate) >= 0:
minimunpaymonth += 10
print "Lowest Payment: " + str(minimunpaymonth)
ok i just solved it. i change the function to give 3 arguments instead of 1
your second loop is checking to see if minimunpaymonth is >= 0, if it is then it performs the loop again.
Your minimunpaymonth will always be >=0 because it starts at 0 & is only ever added to. There is no subtraction from this value.
the second loop keeps adding to minimum payment, it will always be >= 0 till it reaches the numeric limit of the variable; however as the comment pointed out, the "function" could get less, but perhaps the interest rate always keeps the balance above zero and the minimum payments don't get it there -- plausible enough in real life!

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.

Operations with structures, code not working?

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