This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 months ago.
This code should accept three inputs represent the money: "cent", "paper" and "coins", then calculate the total amount of the money:
int coins = 0;
int paper = 0;
int cents = 0;
int transaction = 0;
int total_money = coins + paper + cents;
cout << "Do you want to fill your piggy bank?";
cin >> transaction;
while (transaction != 2)
{
cout << "How many paper money? :";
cin >> paper;
cout << "How many coins ? :";
cin >> coins;
cout << "How many cents? :";
cin >> cents;
cout << "Do you want another transaction?";
cin >> transaction;
if (transaction == 2)
{
cout << "total in piggy bank" << total_money << endl;
}
else
{
cout << "End of the program";
}
return 0;
}
What seems to be the problem here?
You need to do the addition after you get the values from the user, not before.
Like this (for example)
if (transaction == 2)
{
int total_money = coins + paper + cents;
cout<<"total in piggy bank" <<total_money<< endl;
}
A program is a set of statements that are executed in a particular order. Variables in that program are updated at certain points in the execution of the program. If you get your code in the wrong order then the variables are not going to have the values you expect them to.
Related
I keep getting a fixed number for Number of minutes premium service was used and for amount due. I have tried putting parentheses, and it still gives me a fixed number. Also I have tried to change the addition signs for multiplication and still I get a fixed number. If there is anything else wrong with my code please point it out I'd appreciate it.
#include <iostream>
using namespace std;
int main()
{
int Account_Number;
char Service_Code;
float Regular_Service_Standard_Fee = 10.00;
float Regular_Service_Additional_Fee = 0.20;
float Premium_Service_Stanard_Fee = 25.00;
float Premium_Service_Day_Fee = 0.10;
float Premium_Service_Night_Fee = 0.05;
int Regular_Service_Minutes;
int Premium_Service_Day_Minutes;
int Premium_Service_Night_Minutes;
int Total_Premium_Service_Minutes;
float Amount_Due = 0;
cout << "Enter account number. \n";
cin >> Account_Number;
cout << "Enter service code. \n";
cin >> Service_Code;
cout << "Enter number of minutes the service was used. \n";
cin >> Minutes;
if (Service_Code == 'R' || Service_Code == 'r') {
cout << "Regular service selected. \n";
cout << "Enter number of minutes used. \n";
cin >> Regular_Service_Minutes;
}
else if (Service_Code == 'P' || Service_Code == 'p') {
cout << "Premium service selected. \n";
cout << "Enter the number of minutes used during the day. \n";
cin >> Premium_Service_Day_Minutes;
cout << "Enter the number of minutes used during the day. \n";
cin > Premium_Service_Night_Minutes;
Total_Premium_Service_Minutes = Premium_Service_Day_Minutes + Premium_Service_Night_Minutes;
}
else
cout << "Error! Select R or P! \n";
if (Regular_Service_Minutes > 50)
Amount_Due = Regular_Service_Minutes - 50 * Regular_Service_Additional_Fee + Regular_Service_Standard_Fee;
else
Amount_Due = Regular_Service_Standard_Fee;
if (Premium_Service_Day_Minutes > 75)
Amount_Due = (Premium_Service_Day_Minutes - 75) + Premium_Service_Day_Fee;
else if (Premium_Service_Night_Minutes > 100)
Amount_Due = (Premium_Service_Night_Minutes - 100) + Premium_Service_Night_Fee;
else
Amount_Due = Amount_Due + Premium_Service_Stanard_Fee;
cout << "Account # : " << Account_Number << endl;
cout << "Type of service : " << Service_Code << endl;
cout << "Number of minutes regular telephone service was used : "
<< Regular_Service_Minutes << endl;
cout << "Number of minutes premium telephone service was used : "
<< Total_Premium_Service_Minutes << endl;
cout << "Amount Due : " << Amount_Due << endl;
return 0;
}
Hello and welcome to Stack Overflow (SO).
A few pointers:
Try to make your code readable. Refactor! Refactoring will not only show you where your code lacks the attention, but it will expose logical errors too.
Always initialise your variables when they live inside a scope. C++ will initialise your variables only when it comes for free.
#local scope:
void foo()
{
int num; //num is undefined - i.e. garbage value
}
# global scope
int num; //num is 0.
floats should ideally be followed by a .f to avoid converting from a double. ex: float b = 10.0f;
Create a simplified version of your program and run it on rextester.com to make sure that it works, before posting on SO.
I've tried to quickly simplify your code below and it seems to work for me. I'm not sure about the logic of your program though. You may want to revisit a few sections.
The code can be found here. (click on show input and enter the values for the cin before you run the code on rextester)
this is my first time posting on here. Whenever I've gotten stuck on a programming problem, I've typically been able to find enough information to get me unstuck. I'm afraid that the issue I'm having though, I can't quite find an answer to. It's something I'd need someone to look at to tell me what I may be doing wrong in my code.
I have the program running successfully, and it DOES work. The issue however, is that my produced output is off by a few numbers when compared to the expected output on My Programming Lab. I'm really not sure of what to do to produce the correct output. Allow me to post both my source code, and a screenshot MPL's results screen.
SOURCE CODE:
#include <iostream>
using namespace std;
int populationCalculator(int, double, double, int, int);
int main()
{
int startingPopulation, newArrivals, peopleWhoLeft, years,
newPopulation, finalPopulation;
double deathRate, birthRate;
cout << "This program calculates population change.\n";
cout << "Enter the starting population size: ";
cin >> startingPopulation;
while (startingPopulation < 2)
{
cout << "\nThe starting population may not be less than two. Please
re - enter: ";
cin >> startingPopulation;
}
cout << "Enter the annual birth rate (as % of current population): ";
cin >> birthRate;
while (birthRate < 0)
{
cout << "\nBirth rate percent cannot be negative. Please re -
enter:";
cin >> birthRate;
}
birthRate = birthRate / 100;
cout << "Enter the annual death rate (as % of current population): ";
cin >> deathRate;
while (deathRate < 0)
{
cout << "\nDeath rate percent cannot be negative. Please re -
enter: ";
cin >> deathRate;
}
deathRate = deathRate / 100;
cout << "How many individuals move into the area each year? ";
cin >> newArrivals;
while (newArrivals < 0)
{
cout << "\nArrivals cannot be negative. Please re - enter: ";
cin >> newArrivals;
}
cout << "How many individuals leave the area each year? ";
cin >> peopleWhoLeft;
while (peopleWhoLeft < 0)
{
cout << "\nDepartures cannot be negative. Please re - enter: ";
cin >> peopleWhoLeft;
}
cout << "For how many years do you wish to view population changes? ";
cin >> years;
while (years < 1)
{
cout << "\nYears must be one or more. Please re - enter: ";
cin >> years;
}
newPopulation = populationCalculator(startingPopulation, deathRate,
birthRate, newArrivals, peopleWhoLeft);
cout << "\nStarting population: " << startingPopulation << endl;
for (int loopCount = 1; loopCount <= years; loopCount++)
{
newPopulation = populationCalculator(newPopulation, deathRate,
birthRate, newArrivals, peopleWhoLeft);
cout << "Population at the end of year " << loopCount << " is: " <<
newPopulation << endl;
}
system("pause");
return 0;
}
int populationCalculator(int Population, double deathRate, double birthRate,
int newArrivals, int peopleWhoLeft)
{
int newPopulationCount;
newPopulationCount = Population + (Population * birthRate) - (Population
* deathRate) + newArrivals - peopleWhoLeft;
return newPopulationCount;
}
MPL RESULTS:
http://imgur.com/a/mRmpc
I really will appreciate if anyone can help me figure out why my produced output is off by a few numbers.
Step through your code. You're returning an int where you have double and int multiplication. Make sure that you aren't truncating values that might need to be rounded up or down.
Does birth happen before or after death? Should it occur in steps, or all at once like you have shown?
try casting to a double in your operations that involve doubles and integers. For example
birthRate = (double)(birthRate / 100);
deathRate = (double)(deathRate / 100);
Sometimes programming languages will cast a double to an integer, which causes your numbers to be off.
Perhaps the number were rounded off?
I assume this is the case because I noticed you declared some variables in double but the end result is integer. Try to change the data type of the method
populationCalculator(), newPopulation and of course the returning values of the method populationCalculator() from int to double.
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 5 years ago.
Improve this question
Warning: I am brand new to programing! I am trying to create a random letter generator game for a class project. I feel like I have a decent start to it but I am having difficulty with a few points.
The program is supposed to ask the player how many games they would like to play(1-5). The maximum number of guesses they get per game is 5 and then it is supposed to print out what the correct answer was if it was not guessed. As it is, I have it so that it will run the correct number of guesses but not games and it dosent cout<< the correct answer when all guesses are done. Any help is appreciated, thanks.
#include<iostream>;
#include<cstdlib>;
#include<ctime>;
using namespace std;
int main()
{
char alphabet [27];
int number_of_games;
char guess;
int x = 1;
srand(time(0));
int n = rand() % 26 + 1;
cout<<"Weclome to the Letter Guessing game!\n";
cout<<"You have 5 chances to guess each letter.\n \n";
cout<<"How many games do you want to play?\n";
cin >> number_of_games;
cout<<"**************************************************\n\n";
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
if (number_of_games < 1)
{
cout<< "Lets play game " << number_of_games << '\n';
}
//cout << (char)(n+97); //cheat to make sure working
cout<<"Enter your guess: ";
cin >> guess;
int guessValue = int(guess);
if (guessValue > (n+97))
{
cout<<"The letter you are trying to guess is before " <<guess <<"\n";
}
else if (guessValue < (n+97))
{
cout<<"The letter you are trying to guess is after " <<guess << "\n";
}
else if( (char)(n+97))
{
cout << "The answer you were looking for was " << (char)(n+97) << "\n";
}
else
{
cout<<"Your guess is correct! \n";
break;
}
//if answer is not right after x tries, cout the correct answer
x++;
}
system("pause");
return 0;
}
You can use "nested loops" - an outer loop for games, and an inner loop for turns. I've used a for loop in my example.
Also, no need to convert everything to int. char is an integral type and can be used just like a number:
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
// Select a new char (a-z) for each game
char n = 97 + rand() % 27;
cout << "Lets play game " << x << '\n';
// 5 guesses
for (int number_of_guesses = 0; number_of_guesses < 5; number_of_guesses++) {
cout << "Enter your guess: ";
cin >> guess;
if (guess > n)
{
cout << "The letter you are trying to guess is before " << guess << "\n";
}
else if (guess < n)
{
cout << "The letter you are trying to guess is after " << guess << "\n";
}
else
{
cout << "Your guess is correct! \n";
// Break out of the inner for loop, not the while
break;
}
}
x++;
}
I have to write a program that uses a for loop to ask how many floors are in a hotel, then ask the user for the number of rooms on each floor and the number of rooms occupied. At the end I'm to add up all the rooms, how many are occupied and not occupied, and give percentages based on those numbers. So far all I have is the loop, and my sum feature now gives me outrageous numbers.
#include <iostream>
using namespace std;
int main ()
{
int floor, room, occupy, total_unoccupy, total_occupy, total_room;
cout << "How many floors are in the hotel?\n";
cin >> floor;
for ( ;floor >= 1; floor--)
{
cout << "How many rooms are on floor " << floor << "?" << endl;
cin >> room;
cout << "How many of these rooms are occupied?" <<endl;
cin >> occupy;
}
total_room += room;
cout << "The total number of rooms are " << total_room << "." << endl;
return 0;
}
Move total_room += room; inside the for loop.
for ( ;floor >= 1; floor--) {
cout << "How many rooms are on floor " << floor << "?" << endl;
cin >> room;
total_room += room;
cout << "How many of these rooms are occupied?" <<endl;
cin >> occupy;
total_occupy += room;
total_unoccupy += room-occupy;
}
Also, you need to change this line:
int floor, room, occupy, total_unoccupy, total_occupy, total_room;
To this:
int floor = 0, room = 0, occupy = 0, total_unoccupy = 0, total_occupy = 0, total_room = 0;
You should initialize the variables like total_occupy = 0 etc... otherwise you can have unexpected results.
Regards
nothing left to be answered thanks for nhgr
Moreover, in case multiplication, you need to initialize the total variable as 1.
Well I am trying to do an exercise in my programming book and it's difficult for me to grasp exactly what it wants.
My "enterAccountData()" function is suppose to ask the user for an account number and a balance neither of which can be negative and the account number cannot be less than 1000
The second one is the one I am stuck on "computeInterest()" THis function is suppose to accept an integer argument that represents the number of years the account will earn interest. The function then displays the account number from the previous function and displays its ending balance at the end of each year based on the interest rate attached to the BankAccount class. (The interest rate on "BankAccount" has to be a constant static field which is set at 3 percent(0.03)).
So My question is this: How do I set up "computeInterest()" too allow it to calculate the interest using the constant static field when my debugger will not allow me to actually keep the field as a constant? I am not trying to stop any random errors from happening for now, just trying to get the jist of what the book is exactly asking for. Here is my code.
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
private:
int accountNum;
double accountBal;
static double annualIntRate;
public:
void enterAccountData(int, double);
void computeInterest();
void displayAccount();
};
//implementation section:
double BankAccount::annualIntRate = 0.03;
void BankAccount::enterAccountData(int number, double balance)
{
cout << setprecision(2) << fixed;
accountNum = number;
accountBal = balance;
cout << "Enter the account number " << endl;
cin >> number;
while(number < 0 || number < 999)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> number;
}
cout << "Enter the account balance " << endl;
cin >> balance;
while(balance < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> balance;
}
return;
}
void BankAccount::computeInterest()
{
const int MONTHS_IN_YEAR = 12;
int months;
double rate = 0;
int counter = 0;
BankAccount::annualIntRate = rate;
cout << "How many months will the account be held for? ";
cin >> months;
counter = 0;
do
{
balance = accountBal * rate + accountBal;
counter++;
}while(months < counter);
cout << "Balance is:$" << accountBal << endl;
}
int main()
{
const int QUIT = 0;
const int MAX_ACCOUNTS = 10;
int counter;
int input;
int number = 0;
double balance = 0;
BankAccount accounts[MAX_ACCOUNTS];
//BankAccount display;
counter = 0;
do
{
accounts[counter].enterAccountData(number, balance);
cout << " Enter " << QUIT << " to stop, or press 1 to proceed.";
cin >> input;
counter++;
}while(input != QUIT && counter != 10);
accounts[counter].computeInterest();
system("pause");
return 0;
}
The constant field is easy enough:
class BankAccount
{
...
const static double annualIntRate = 0.03;
...
}
(Does your debugger complain about that? I'm using gcc 4.2.1) But there are other troubling things in your code, like the way computeInterest tries to set rate to zero, and the while loop... needs work.
EDIT:
One good principle is worth a hundred specific corrections. When you develop a complicated function, don't try to do it all at once; start with a simple piece, get that working perfectly, then build up. F'rinstance, computeInterest. You have several independent parts to get working: going through the while loop the correct number of times, calculating interest increments, keeping track of the balance-- right now computeInterest does none of these correctly. Tackle them one at a time, or in parallel if you want, but never combine parts that don't work.
boy it's been a LONG time since I've worked in C++, but I think all you have to do is this:
static double annualIntRate =.03;
in the "private" section of your code.
and then you can use annualIntRate as though it was a global (to each instance of the class) variable.