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.
Related
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.
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)
I have been working on a simple grade calculator, I am having trouble with the "labs" option spitting back a bad result, I am looking for a decimal percent, but I keep getting a very very large exponential number.
The specific part I am having trouble with is the calclabavg() function-- the for loop to be exact.
I am not asking for an exact solution, I just want to be pointed in the right direction so that I can solve the problem on my own.
Thanks so much in advance :)
float calclabavg(){//funciton that calculates user lab averages
float x, vary, pointspos, sumpointspos, sumearned;
cout << "How many labs in labs?" << endl;
cin >> x;
float totalpoints = 0;
cout << "Do the points vary per lab? (Press 1 for yes, 0 for no)" << endl;
cin >> vary;
if (vary == 0){
cout << "How many points were possible on each lab?" << endl;
cin >> pointspos;
sumpointspos = x * pointspos;
}
for (int i = 0; i < x; i++){
float temp;
cout << "What was your score on lab " << i + 1 << endl;
cin >> temp;
sumearned += temp;
if (vary == 1){
cout << "How mant points possible on lab " << i + 1 << endl;
float pointsposvary;
cin >> pointsposvary;
sumpointspos += pointsposvary;
}
//pointspos = pointspos + temp;
}
return sumearned / sumpointspos;
}
It seems as if you do not initialize sumearned.
Statement sumearned = 0.0; at the beginning of calclabavg should bring you at least a step further. BTW: initialising also the other variables is good practice and makes code more stable.
I'm trying to loop the assignment scores and totals based on whatever the user inputs in for n. I have been searching around and just hitting duds, which is what the whole deal with the int i variable is at the moment. I can't get things to loop properly and right now this doesn't even compile because of that pesky i I have in there. You take out that i and the program runs fine with the exception that nothing becomes of the n input.
/**
File: project_2_14.cpp
Description: Write a program that calculates the total grade for N classroom exercises as a percentage. The user should input the value for N followed by each of the N scores and totals. Calculate the overall percentage (sum of the total points earned divided by the total points possible.) and output it as a percentage. Sample input and output is shown below.
Created: Friday, September 11th, 2015
Author:
email:
*/
#include<iostream>
#include<vector>
using namespace std;
int main()
{
float s; // assignment score
float t; // total points worth
float p; // percentage
int n = 0;
//input the number of assignments
cout << "How many assignments are there? " << endl;
cin >> n;
for (int i=0; i < =n; i++)
{
//input the total points earned for assignment
cout << "What is the score earned for this assignment? ";
cin >> s;
//input the number of points assignment is worth
cout << "How many points was the assignment worth? ";
cin >> t;
//calculate percentage
p = (s / t)*100;
}
//output score
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "Total score: " << p << "%"<< endl;
return 0;
}
You should remove the int n = 0; and it should be simply int n.
and you should use <=, without any spaces between both characters.
EDIT:
As you can see here: http://ideone.com/SeNum8 it already loops correctly :)
#include<iostream>
#include<vector>
using namespace std;
int main()
{
float s; // assignment score
float t; // total points worth
float p; // percentage
int n;
//input the number of assignments
cout << "How many assignments are there? " << endl;
cin >> n;
for (int i=0; i <=n; i++)
{
//input the total points earned for assignment
cout << "What is the score earned for this assignment? ";
cin >> s;
//input the number of points assignment is worth
cout << "How many points was the assignment worth? ";
cin >> t;
//calculate percentage
p = (s / t)*100;
}
//output score
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "Total score: " << p << "%"<< endl;
return 0;
}
Could some one help me with this?
I've racked my head over an hour and I can't get it to work.
This is in C++ and I've been learning for a little bit but I'm still new...
int main()
{
double rate, amount,time, S;
cout << "Insert the time of the super: ";
cin >> time;
cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
cin >> rate;
cout << "Insert the amount $: ";
cin >> amount;
S =("amount * (rate ^ time - 1)", pow(rate,time));
cin >> S;
cout << "The total amount is: " << "S /(rate - 1)" << endl;
system("PAUSE");
return 0;
}
i dont get a compile error but i can never get an answer from it
You "never get a result" because you're setting S to the result of pow with comma operator weirdness then assigning to it again with the line
cin >> S;
which is waiting for you to input another number.
You have two main problems. Here is the updated code with comments on the altered parts:
int main()
{
double rate, amount,time, S;
cout << "Insert the time of the super: ";
cin >> time;
cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
cin >> rate;
cout << "Insert the amount $: ";
cin >> amount;
S = amount * pow(rate, time - 1); // take away the quotes and don't make pow seperate
cout << "The total amount is: " << (S /(rate - 1)) << endl; // do the calculation and output it
system("PAUSE");
return 0;
}
Remember that things inside quotes "like this" are string literals, so "4 * 4" is a string but 4 * 4 (see the absence of quotes) does multiplication which yields the number 16.
I don't think you should assign values to S the way you are doing it. S is declared as double and you are assinging a string to it initially. And when you output the result you are also enclosing the calculation in quotes. You should simply cout << S / (rate-1); // without quotes or cout will simply output the string