So in my little game, there is a happiness mechanic, I want it to be capped at 100, and show the player how much happiness they lost due to the overflow, but it keeps showing 100. (I created the integer happiness at the very start), its in a switch statement, all other parts of the switch work well.
case 5:
if (happiness <= 100) {
happiness = happiness + 20;
cout<< "The festival goes well";
if (happiness > 100) {
int lost_happiness = happiness - (happiness%100);
happiness = happiness - (happiness%100);
cout << ", however, happiness has reached the cap of 100. The amount lost is " << lost_happiness;
}
}
break;
Any ideas why?
From what I understand case 5 is always showing 100 and it should . Just think let initial happiness be 95 , you add 20 it becomes 115 .then you are subtracting 115%100 I.e. 15 from it , so the answer will become 100 in every case .
You are using the same formula to calculate both the lost_happiness and new happiness values:
int lost_happiness = happiness - (happiness%100); // Notice the similarity
happiness = happiness - (happiness%100); // in the two RHS codes?
This is incorrect, and the former should just be happiness % 100.
if (happiness <= 100) {
happiness += 20;
cout<< "The festival goes well";
if (happiness > 100) {
int lost_happiness = happiness % 100; // DON'T subtract this from total
happiness -= lost_happiness; // No need to recalculate the "%"
cout << ", however, happiness has reached the cap of 100. The amount lost is " << lost_happiness;
}
}
Note that I have also used some techniques to make your code rather more succinct; please feel free to ask for further details and/or clarification.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My program needs to be able to calculate the monthly phone bill and there are 3 plans: Basic where 10 hours are free and it costs 9.95, Gold where 20 hours are free and it costs 14.95, and Platinum where you have unlimited hours and it costs 19.95. When my program is given hours less than the free hours it subtracts them from the initial cost, and also it has build hours.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Set up the variables.
string input;
int hours;
int basicHours;
int goldHours;
float extraBasic;
float basicCost;
float goldCost;
// Will ask and display the user their plan and hours.
cout << "Hello! Welcome to the Comms4You Telecom Company!" << endl;
cout << "Please provide your plan." << endl;
cin >> input;
cout << input << ", Ok now please provide the amount of hours you used." << endl;
cin >> hours;
//Calculate different equations
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
//This part is for displaying to the users plans and hours.(Also calculations)
if (input == "Platinum") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $19.95.";
}
else if (input == "Gold") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << goldCost << ".";
}
else if (input == "Basic") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << basicCost << ".";
}
else
return 0;
}
The problem is in these lines:
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
Think about what they are doing.
basicHours = (hours - 10);
If hours was 11, then basicHours is now 11 - 10 = 1. This is good. But if hours was 9, then basicHours is now 9 - 10 = -1. This is not what you want; if I used less than my 10 free hours, then you want basicHours to be 0.
So you can write instead:
if (hours > 10) {
basicHours = hours - 10;
}
else {
basicHours = 0;
}
or equivalently:
basicHours = (hours > 10) ? hours - 10 : 0;
goldHours = (20 - hours)
This should be the exact same thing as basicHours, except with 20 instead of 10! I will let you adapt the above code.
basicCost = (9.95 + extraBasic); and goldCost = (14.95 + goldHours);
This is wrong. 9.95 is a monetary value, say in euros. extraBasic is a time, in hours. You cannot add hours with euros! If I used 12 hours with the basic plan, what is the result of 9.95€ + 2h? I do not know, it does not make sense.
If I used 12 hours with the basic plan, then I have to pay 9.95€, and I have to pay for the extra 2h. What is the cost of the extra 2h? It is 2 times the cost of an hour; in other words, it's the extra time multiplied by the hourly rate. You should have a constant variable called hourlyRate or basicHourlyRate in your program, with that value. Then you can write:
basicCost = 9.95 + extraBasic * basicHourlyRate;
goldCost = 14.95 + goldHours * goldHourlyRate;
Coding style: separate data and code
A good rule to follow is never to put data in your code. All literal values are data. The cost of the basic and gold and platinum plans are data. The hourly rate is data. The number of "free" hours for each plan is data. Define a few variables with explicit names, initialize those variables with the data at the very beginning of the code, then write the rest of the code without ever using a literal value. There are two reasons why this is important.
The code will be easier to read with variables. Explicit names in variables make the code meaningful; if you use literal values inside the code, the people reading your code don't know what those values stand for. Why do you subtract 10 from hours? We have to think about where this 10 comes from. However, if you write basicPayingHours = hours - freeBasicHours, we understand immediately. "The people reading your code" include StackOverflow members you're showing your code to, but also your schoolmates or coworkers, your teacher or boss, and most importantly, yourself when you read your code again six months from now.
When the data changes, it will be a lot easier to update your code if data is cleanly separated from code. Imagine you are working for this phone company. Next year, they update their plans and the basic plan is now 9.99 per month instead of 9.95. If this value is stored at the beginning of your code in a line basicPlanInitialCost = 9.95;, it is very easy to update it. However if there are multiple occurrences of 9.95 in your code, you will have to track them and change them all manually - this process is very prone to errors for two reasons: you might accidentally change the cost of something else that also costs 9.95; you might forget to update values that are dependent on the monthly price of the basic cost (like the yearly price of the basic cost, which is 12 * 9.95 = 119.40).
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!
I am asked, after giving me
an initial_population(7),
a growth_rate(1.2%),
an initial_year (2011), and a formula that link the final population to the inital one with the following :
initial_population * exp ( (final_year - initial_year) * (rate/ 100.0))
For a certain population entered, I have made this population grow year after year with this following forumla :
double pc(0.0); // pc = population entered
while (pc <= initial_population)
{
cout << "How many billion (> 7) ? ";
cin >> pc;
};
int temp(year);
do {
++temp;
cout << "Population in " << temp << " : " <<
initial_population * exp ( (final_year - initial_year) * (rate/ 100.0))
<< endl;
}
while ( pc > initial_population *
exp ( (final_year - initial_year) * (rate/ 100.0)));
I would like now to make this population growth_rate being divided by two anytime the initial population doubles and to make it show until the population has reached the entered population "pc". Obviously, the process must take longer than when the growth_rate wasn't divided and the outcome should look like :
Population in 2012 : 7.085 ; growth rate : 1.2 %
Population in 2013 : 7.17 ; growth rate : 1.2 %
Population in 2014 : 7.257 ; growth rate : 1.2 %
Population in 2015 : 7.344 ; growth rate : 1.2 %
...
Population in 2068 : 13.87 ; growth rate : 1.2 %
Population in 2069 : 14.04 ; growth rate : 0.6 %
Population in 2070 : 14.12 ; growth rate : 0.6 %
...
Population en 2195 : 29.02 ; growth rate : 0.3 %
All I know in C++ yet is until the for and do while loops, with of course the if else statements.
Is there anyonone who can help me with that, I don't need to have the perfect answer, just some help on how to start with this part. for example how to make the statement when the population doubles, etc.. ?
Thanks a lot.
Save the initial_population value, multiplied by 2, in a separate variable. Then check on each iteration if the current_population (a variable I made up, but it's value should be obvious) is greater than or equal to the other stored variable, multiply the value by 2 again and split the growth rate in half. Something like this:
double population_doubled_check_val = initial_population * 2;
double current_population;
do {
++temp;
current_population = initial_population * exp ( (final_year - initial_year) * (rate/ 100.0));
cout << "Population in " << temp << " : " << current_population << endl;
if (current_population >= population_doubled_check_val) {
population_doubled_check_val *= 2;
rate /= 2;
}
}
while ( current_population < pc );
I don't think copypasta of that will work, but it should give you an idea. On an aside, it's helpful if you provide a full, minimum implementation necessary to exemplify the problem but still compiles. For no other reason than to get answers faster. :)
I'm just starting to learn c++ i just want to ask how can I loop this? Please, don't give me direct answer give me a clue or just a "work frame" how to solve this problem. I want to solve it on my own.
So I'm kinda getting difficulties in looping decimals only i can loop solid numbers but i have some troubles looping decimal figures.
P.S Im reviewing for an exam 4 hours from now but this might come up, i having difficulties in this types of question.
This is the question:
Shipping Cost Calculator
A mail order company charges $3.00 for handling, free shipping for orders 10 pounds or less, plus $0.25 for each pound over 10. Write a program that repeatedly asks the user for the weight of an order, then writes out the shipping charge. The program stops when a weight of zero or less is entered.
Weight of Order:
5
Shipping Cost: $3.00
Weight of Order
20
Shipping Cost: $5.50
Weight of Order
0
bye
I keep on practicing to this but i seem to find error on a formula
how can I loop 3.25 to 4.50 to 5.75 to 6.00 and so on?
main() {
float a, b, x;
printf("Enter Weight: ");
scanf("%f", &a);
if (a <= 10)
{
printf("Your balance is 3.00");
}
else if (a > 10)
{
for (x =.25; x <= a; x++)
{
printf("Your balance is %.2f \n", a);
a += + .25;
}
}
else if (a == 0)
{
printf("Bye");
}
getche();
}
for ( double x = 3.25; x <= so_on; x += 1.25 ) { /*...*/ }
or
for ( float x = 3.25f; x <= so_on; x += 1.25f ) { /*...*/ }
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am new to c++. The problem consists in minimizing the number of coins required to give the exact change I have 25 10 5 and 1 cent coins.
For example if a customer is owed $3.20 the number of coins to give would be 14 (12 of 25 and 2 of 10).
My problem:
A number like 4.20 says you need 22 coins instead of 18. I know the problem is generated when it multiplies change by 100. I get 419 instead of 420.
Here is my code.
int coins = change * 100;
//How many 25 cent coins you need
if (coins >= 25)
{
quarter = coins / 25;
coins = coins % 25;
}
//How many 10 cent coins you need
if (coins >= 10)
{
dimes = coins / 10;
coins = coins % 10;
}
//How many 5 cent coins you need
if (coins >= 5)
{
nickels = coins / 5;
coins = coins % 5;
}
//How many 1 cent coins you need
if (coins >= 1)
{
pennies = coins / 1;
coins = coins % 1;
}
NumCoins = quarter + dimes + nickels + pennies;
printf("%d \n", NumCoins);
Thanks for your help.
#include<iostream>
using namespace std;
int main()
{
int amount = 420;
int coins[] = { 25, 10, 5, 1 };
int ncoins = 0;
for( int i=0 ; i<sizeof(coins)/sizeof(int) ; ++i )
{
ncoins += amount / coins[i];
amount %= coins[i];
}
cout << "You need " << ncoins << " coin(s)." << endl;
}
You need 18 coin(s).
It is easy to track which specific coins are needed in the for loop. I assume the reader can adjust the code as needed to suit their purposes.
From my understanding of the problem my suggestion on how to do this is essentially having two variables. change (This is the change you have in cents.) as well as coins (This is the total number of coins you need to make change.)
Then once you have the change, you keep subtracting the quarters (that is 25), from the change variable until it is less than 25, then you move onto dimes, nickels and finally pennies. At the same time you decrement the change variable, you increment the coins in order to keep track of the minimum number of coins you need. This should be much cleaner and simpler than keeping track of all these other variables.
Some pseudocode could look like this:
declare variables
do loop of change > 25
change = change - 25
coins = coins + 1
do loop of change > 10
...
(keep doing this for dimes, nickels and pennies)
...
display number of coins needed.