This is my attempt at a solution I wrote for an exercise in Bjarne Stroustrup's Programming Principles and C++ book. Unfortunately, the section I wrote to give the total amount of money from the coins entered is not working how I would like!
A quick answer and I would be very grateful but if anyone also has the time could they help me introduce some basic error checking?
The way I would want it to work would be after a user input is required (e.g How many 20p's do you have?), to check whether or not the user inputted an int. If not, provide a subtle error message and a chance to repeat the same question, rather than stop the program or start the program from the beginning!
#include "../../std_lib_facilities.h"
int main() {
int one, ten, twenty, fifty, one_pound, two_pound;
double amount;
amount = (one * 0.01) + (ten * 0.1) + (twenty * 0.2) + (fifty * 0.5) + one_pound + (two_pound * 2);
cout << "Welcome to the change counter app!\nHow many 1p's do you have?\n";
cin >> one;
cout << "How many 10p's do you have?\n";
cin >> ten;
cout << "How many 20p's do you have?\n";
cin >> twenty;
cout << "How many 50p's do you have?\n";
cin >> fifty;
cout << "How many £1 coin's do you have?\n";
cin >> one_pound;
cout << "How many £2 coin's do you have?\n";
cin >> two_pound;
cout << "You have: " << one << " 1p coins!\n"
<< "You have: " << ten << " 2p coins!\n"
<< "You have: " << twenty << " 20p coins!\n"
<< "You have: " << fifty << " 50p coins!\n"
<< "You have: " << one_pound << " £1 coins!\n"
<< "You have: " << two_pound << " £2 coins!\n"
<< "The total amount of money you have is: " << amount << "\n";
}
You have two problems:
The first is that in the absence of loops, code runs from top to bottom. That means you calculate amount before you read the input.
The second problem is that when you calculate amount (currently, in the wrong place) you use the variables one, ten, etc. before they are initialized. Uninitialized local variables will have an indeterminate value, and using them will lead to undefined behavior.
The simple solution to both problems is to move the calculation of amount to after you have read the input, but before you write the output.
Related
Essentially, I want the output to look like the first photo, but my output is in the 2nd (both attached). I attached my code snippet as well to show what I am trying.
Any help would be appreciated, I have solved all logical errors in this program and just need help formatting. Also, is there any better way to keep all of the inputs and calculated values on the right side, or do I just need to throw in the \t a couple times like I did? Thanks!
I want my code to look like this:
But keep getting this:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double loanAmount, interestRate, paymentsNum;
//Stores the loan amount value into memory
cout << "Loan Amount: \t\t\t$ ";
cin >> loanAmount;
//Stores the monthly interest rate value into memory
cout << "Monthly Interest Rate: \t\t";
cin >> interestRate; cout << '%' << endl;
interestRate = interestRate / 100;
//Stores the nuumber of payments value into memory
cout << "Number of Payments: \t\t";
cin >> paymentsNum;
//Calculates the payment on a loan
double payment = (interestRate * pow((1 + interestRate), paymentsNum)) / (pow((1 + interestRate), paymentsNum) - 1);
//Calculates the monthly payment on a loan
double monthlyPayment = payment * loanAmount;
cout << "Monthly Payment: \t\t$ " << monthlyPayment << endl;
//Calculates the total amount paid back from the original loan amount
double paidBack = monthlyPayment * paymentsNum;
cout << "Amount Paid Back: \t\t$ " << paidBack << endl;
//Calculates the total interest paid on the loan
double interestPaid = paidBack - loanAmount;
cout << "Interest Paid: \t\t\t$ " << interestPaid << endl;
return 0;
}
cin >> interestRate;
At this point your program stops and waits for you to type a line of text following by the Enter key, which gets echoed back, the Enter key causes the cursor to move to the next line.
cout << '%' << endl;
Only after the cursor moves to the next line does this output take place. The fact that in the source file this statement is on the same line is immaterial. The output of the C++ program does not depend on how its source code is formatted, C++ does not work this way. C++ is whitespace-agnostic, a C++ program can be indented in any way and its spacing is completely arbitrary, without affecting its functionality.
It is not possible to get the behavior you want from a basic C++ program that uses basic C++ input and output, via std::cin and std::cout, in a portable manner. On an outside chance you can consult the documentation for your operating system, to determine if there are special terminal character sequences that can be used to move the cursor to the previous line and position it at a (guessed) column where the % would go. This would be specific not just to your operating system but also to whatever terminal program you are using.
I figured out a workaround to this. To get my desired output I used:
cout << "Loan Amount: " << right << setw(20) << "$ ";
cin << loanAmount;
cout << "Monthly Interest Rate: " << setw(12) << "%\b\b";
cin >> interestRate;
interstRate = interestRate / 100;
Not sure if this is the best idea, but it worked. I'm not too worried about fixing this minor issue, but I ended up just stumbling upon this again while watching some videos online.
I just started my C++ class 2 weeks ago at my college and we have our first homework assignments. I'm gonna copy paste the instructions first and then my code to help you understand what my professor is asking for and then show you where I am stuck.
"The program needs to calculate the number of remaining explorers after the battle and the number of extra gold pieces the player keeps after the gold pieces are divided evenly between the surviving explorers (in the above example each of the 4 surviving explorers got 187 gold pieces and the two remaining pieces that couldn't be divided evenly between the 4 explorers go to the player (quest leader))."
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double numExplorers;
double numLost;
double numSurvived;
double extraGold;
cout << "Welcome to Lost Fortune!" << endl << endl
<< "Please enter the following questions for your personalized adventure: " << endl << endl
<< "Enter the number of Explorers: " << endl;
cin >> numExplorers;
cout << "Enter the number of Explorers Lost in Battle: " << endl << endl;
cin >> numLost;
numSurvived = numExplorers - numLost;
extraGold = 750 / numSurvived;
cout << "You bravely led " << numExplorers << " adventurers on a quest for gold." << endl
<< "The group fought a band of ogres and lost " << numLost << " members." << endl
<< "Only " << numSurvived << " survived." << endl << endl
<< "The party was about to give up when they stumbled upon the" << endl
<< "buried fortune of 750 gold pieces. The group split the loot evenly" << endl
<< "and as the qeust leader you kept the extra " << fixed << setprecision(1) << extraGold << " gold pieces." << endl;
system("PAUSE");
return 0;
}
That is my current code. Our professor has numerous examples we need to plug our program into to test against, but I'll provide one set of the numbers. The number of explorers is 17 and the number lost is 13. That leaves 4 remaining. The 750 pieces (It is always 750 as per professor's instructions for this program) are supposed to be divided amongst the 4 players evenly leaving us with 187.5 per player.
The 0.5 * 4 players leaves us with 2 remaining pieces that can't be evenly distributed and thus we (quest leader) are supposed to keep it. How do I write a formula for this?
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 7 years ago.
Improve this question
I am using orwell dev| c++
C++ is a new language to, i am coming from c# which is like i would say 70% the same.
here is my code
#include<iostream>
#include<fstream>
using namespace std;
///loading libraries
float const taxnet = .9;
float const taxwh = .1;
int employeenumber;
float payrate, gross, net, manhours, overtime, taxes;
///declaring variablies and costants
char more;
char more2;
///user controls
///payroll calculations function
void payrollcalc () {
if (manhours>40) {
overtime= manhours-40;
gross= ((manhours - overtime) * payrate)+((payrate * 1.5)* overtime);
//overtime claculation
}
else {
gross =manhours * payrate;
//no overtime calculation
}
taxes= gross * taxwh;
net = gross * taxnet;
//taxesand net pay calculation
cout<< " Your ID is " << employeenumber <<endl;
cout<< " # of hours worked " << manhours << endl;
cout<< " Your Hourly rate is " << payrate << endl;
cout<< " Your Gross pay is " << gross << endl;
cout<< " Your tax rate is " << taxwh << endl;
cout<< " Amount of taxes " << taxes << endl;
cout<< " Your net pay is " << net << endl;
///writing to file
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open (empnum+".txt");
payroll<< " Your ID is " << employeenumber <<endl;
payroll<< " # of hours worked " << manhours << endl;
payroll<< " Your Hourly rate is " << payrate << endl;
payroll<< " Your Gross pay is " << gross << endl;
payroll<< " Your tax rate is " << taxwh << endl;
payroll<< " Amount of taxes " << taxes << endl;
payroll<< " Your net pay is " << net << endl;
payroll.close();
}
main(){
while (more != 27){
//main
cout<< "Hit 1 to enter data hit 2 to recall dat hit esc to exit";
///instructions
newdata:
///call back see line 115
if (more == 49) {
cout<< "Enter Employee ID:";
cin>> employeenumber;
cout<<"Enter Number of Hours Worked:";
cin>> manhours;
cout<<"Enter Pay rate:";
cin>> payrate;
cin>> payrollcalc;
}
else (more == 50) {
olddata:
///call back see line 111
errorreset:
cout<< "Enter employee number";
cin>> employeenumber;
///reading in data
ifstream payroll = employeenumber;
payroll.open(employeenumber".txt");
if (!payroll){
cout>> "Check employeenumber and try agian" endl;
goto errorreset:
///error check
}
cout>> payroll.eof endl;
cout>> endl;
cout>> endl;
cout>> "Press Enter to see another employee number; Press space to enter new employee information; press escape to exit the program" endl;
if (more2 == 13 ){
goto olddata;
}
else (more2 == 32){
goto newdata;
}
///sending back to the loop
}
//entering data
return 0;
}
}
I think my issues is in this segment
std::string empnum = std::to_string(employeenumber);
ofstream payroll;
payroll.open (empnum+".txt");
payroll<< " Your ID is " << employeenumber <<endl;
payroll<< " # of hours worked " << manhours << endl;
payroll<< " Your Hourly rate is " << payrate << endl;
payroll<< " Your Gross pay is " << gross << endl;
payroll<< " Your tax rate is " << taxwh << endl;
payroll<< " Amount of taxes " << taxes << endl;
payroll<< " Your net pay is " << net << endl;
payroll.close();
If some can step me through where i am going off the rails i would be grateful because i am out of ideas.
First off consider turning up the error/waring level of your compiler, for gcc/clang a sensible level would be -Wall -Wextra for a start.
Let me go through some of the problems I see in your code.
main(){
We got a first problem here already. The only 2 signatures allowed for the main function in C++ are int main() or int main(int argc, char *argv[]). Yours might be accepted due to legacy reasons (implicit return type of int in C if you don't specify any) but shouldn't be used.
cout>> payroll.eof endl; // this line absolutely makes no sens and you forgot some `<<` in here probably.
cout>> endl;
cout>> endl;
cout>> "Press Enter to see another employee number; Press space to enter new employee information; press escape to exit the program" endl;
The 'arrows' point into the wrong direction. It should be cout << endl. To remember it see them as arrows that signify the data flow. cin >> variable the data is read from cin and gets put into the variable, cout << variable the variable gets output into cout.
Then you got a read that doesn't make sense:
cin>> payrollcalc;
payrollcalc is a function, I don't know what you wanted to do here, but you should probably call it like payrollcalc();, trying to read from cin into it doesn't make sense.
You're also using std::string without #include <string>. Also note that you should probably put a space in the include line like I did. I don't know if it's a problem without space of the top of my head but it's certainly more readable with a space.
Now for some bad practices and other stuff that I should probably point out. Your indentation and formatting were very messy and made it hard to spot anything you should probably see into cleaning it up a bit.
As for goto it's considered bad practice/harmful. This was started by Dijkstra. Now to say it got it's uses still in some places and is often over exaggerated but for the simple code you're using I don't think it's necessary and could probably be done in a better more structured way that makes the logic easier to understand, remember code is read far more often than you write it and readability is very important. If you're curious about the problems, #itsnotmyrealname posted a link on your question already for you to look through.
Also you got inconsistencies that make it harder to read/confusing.
gross =manhours * payrate; // inconsistent assignments
taxes= gross * taxwh;
net = gross * taxnet;
std::to_string(employeenumber) // inconsistent function calls.
payroll.open (empnum+".txt");
As for the global variables if you've already got some experience in programming (in C# like you said) then you probably know that they are considered bad practice too and should be avoided, you should look into making them local variables and passing them around as function arguments/returning them from functions.
This is my first program its to calculate commute cost. Visual Studio is having issues debugging so Im looking for some help...
#include <iostream>
using namespace std;
int main()
{
int miles, gallons, gallonCost, mpg, mileCost, parking, tolls, FuelCost, TotalCost = 0.0;
Can someone explain what the above line is doing (or not doing) is it a correct way to make a list of float integers?
cout << " How many miles do you drive per day? ";
cin >> miles;
cout << " What is the price per gallon of fuel? ";
cin << gallonCost;
cout << " How many gallons of fuel do you use per day? ";
cin >> gallons;
mpg = miles / gallons;
mileCost = gallonCost / mpg;
cout << " Your fuel efficentcy is " << mpg ;" miles per gallon. ";
cout << " Your fuel cost is $" << mileCost ;" per mile. ";
FuelCost = mileCost * miles;
cout << " Your paying $" << FuelCost ;" for fuel per day.";
cout << " What are you daily parking fees? ";
cin << parking;
cout << " How much do you spend on Tolls each day? ";
cin >> tolls;
TotalCost = parking + tolls + FuelCost;
cout << " Your driving cost is $" << TotalCost ;" per day." endl;
system("PAUSE");
return 0;
}
Thanks in advance
No that is not the way to create floating point variables, but the way to create integer variables. There is no such things as "float integers".
You should also get a lot of warnings about expressions not doing anything, like in the line
cout << " Your fuel efficentcy is " << mpg ;" miles per gallon. ";
// Problem here ^
That is because you have an extra semicolon in the middle of the line, thereby terminating the output statement. Then the compiler finds a string, which is the same as an expression so it's okay but doesn't do anything which should cause a warning. Instead of the extra semicolon I suspect you wanted the output operator <<.
And you should be getting an error on this line:
cout << " Your driving cost is $" << TotalCost ;" per day." endl;
// Error here ^
That error is because you have a string followed by an identifier. This is not a valid expression. You probably forgot the output operator << here.
It's this last error that causes the build process to not create an executable, so you can't run/debug. Always pay attention to the messages produced by the compiler, even warnings will tell you something useful.
I am trying to write a code that ask the user how much money they have and how much the item cost they want to buy. Then it will tell them how many of the item they can buy and how much money they will have left over. I am a beginner and not sure what to do. The modulus operator is only giving me 0.00 and when I take away the (int) in front of my variables it give me an error. I want them as doubles but it gives an error.Thank you.
void howMany (double &amtMoney, double &itemCost)
{
int amtItem;
double remainingMoney;
cout << "Please enter amount available and cost of each ";
cin >> amtMoney >> itemCost;
if(amtMoney < 0)
{
cout << "Invalid price " <<endl;
}
else
{
amtItem = amtMoney / itemCost;
(double)remainingMoney = (int)amtMoney % (int)itemCost;
cout << fixed << setprecision(2) << "You can buy " << amtItem <<
" and have " << remainingMoney << " left over. " <<endl;
cout << endl;
}
}
No sure what type amtMoney and itemCost are, but you can use fmod to safely evaluate a remainder. You just need to include cmath library.
Also, you don't need to write (double)remainingMoney cause remainingMoney is declared as double.