I am working on a programming challenge from "Starting Out With C++: Early Objects, 10th Edition". I have the code about halfway done, but the output isn't coming out how it is supposed to be, and I am wondering how to fix it. I have it attached here and the desired output.
#include <iostream>
using namespace std;
int main()
{
float starting_num_of_organisms,
average_daily_population_increase,
size_of_daily_population;
int num_of_days_to_multiply;
cout << "Enter Starting Population: ";
while (!(cin >> starting_num_of_organisms) || starting_num_of_organisms < 2) {
cout << "Invalid. Population must be 2 or greater.";
cout << "Enter starting population: ";
cin.clear();
cin.ignore(123, '\n');
}
cout << "Enter positive daily growth % (.1 must be entered as 10): ";
while (!(cin >> average_daily_population_increase) || average_daily_population_increase < 0) {
cout << "Invalid. Daily Population Growth \n"
<< " must be greater than 0. \n"
<< "Enter Daily Population Growth (%): ";
cin.clear();
cin.ignore(123, '\n');
}
average_daily_population_increase *= .01;
cout << "Enter number of days to calculate: ";
while (!(cin >> num_of_days_to_multiply) || num_of_days_to_multiply < 1) {
cout << "Invalid. Number of days must not be less\n"
<< "than 1. Enter number of days to calculate: ";
cin.clear();
cin.ignore(123, '\n');
}
for (int i = 0; i < num_of_days_to_multiply; i++) {
cout << "Population size for day " << (i + 1);
cout << ": " << starting_num_of_organisms
<< endl;
starting_num_of_organisms += (starting_num_of_organisms * average_daily_population_increase);
}
return 0;
}
Here is the current output:
Enter Starting Population: 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate: 8
Population size for day 1: 896.896
Population size for day 2: 921.875
Population size for day 3: 947.549
Population size for day 4: 973.938
Population size for day 5: 1001.06
Population size for day 6: 1028.94
Population size for day 7: 1057.6
Population size for day 8: 1087.05
The desired output is something like this below. The numbers are just for reference, and do not have to be specific to those numbers.
Enter starting population (greater than 2): 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate (greater than 1): 8
----------------------------------
Start Population: 896.90
Daily Percent Growth: 2.79%
Number of Days: 8
Day Start End
Popl. Popl.
----------------------------
1 896.90 921.87
2 921.87 947.55
3 947.55 973.94
4 973.94 1001.06
5 1001.06 1028.94
6 1028.94 1057.60
7 1057.60 1087.05
8 1087.05 1117.33
It appears as though your code does the correct calculations. Just format the output and it will look like the desired output.
printf("%-10s%10s%10s\n", "day", "start", "end");
for(int i = 0; i < 30; i++)
printf("=");
printf("\n");
for (int i = 0; i < num_of_days_to_multiply; i++)
{
printf("%-10u%10.2lf", i + 1, starting_num_of_organisms);
starting_num_of_organisms +=
(starting_num_of_organisms *
average_daily_population_increase);
printf("%10.2lf\n", starting_num_of_organisms);
}
Note I used printf from the C libs (<stdio.h>), but the same can be achieved with cout, just much more verbose.
Output:
Enter Starting Population: 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate: 8
day start end
==============================
1 896.90 921.87
2 921.87 947.55
3 947.55 973.94
4 973.94 1001.06
5 1001.06 1028.94
6 1028.94 1057.60
7 1057.60 1087.05
8 1087.05 1117.33
Related
Need to take out the highest and lowest numbers of 5 judges 0 to 10 on the score
cout << "Please enter the name of the athelete.\n";
getline(cin, name);
cin >> name;
cout << "Please enter the first judge's score below\n";
cout << "Please enter a score between 0 and 10.\n";
cin >> First_Score;
Pseudo code
loop for 5 answers
sort them
sum of middle 3
avg sum / 3
print
The simplest solution would be to create two additional variables. The first, 'lowest', to store the lowest value and the second, 'biggest' to store the biggest value.
int lowest = 0, biggest = 11;
...
cin >> First_Score;
while (First_Score < 0 || First_Score > 10)
{
cout << "That is not a valid input, please pick between 0 and 10.\n";
cin >> First_Score;
cout << "Your selection was " << First_Score << endl;
}
lowest = First_Score;
biggest = First_Score;
...
And then for each judge :
cout << "Please enter the fifth judge's score here below\n";
cin >> Fifth_Score;
while (Fifth_Score < 0 || Fifth_Score > 10)
{
cout << "That is not a valid input, please pick between 0 and 10.\n";
cin >> Fifth_Score;
cout << "Your selection was " << Fifth_Score << endl;
}
if(lowest > Fifth_Score)
lowest = Fifth_Score;
if(biggest < Fifth_Score)
biggest = Fifth_Score;
...
int sum = Avg_Score = (First_Score + Second_Score + Third_Score + Fourth_Score + Fifth_Score);
Avg_Score = (sum - lowest - biggest) / 3;
...
Always separate input and logic.
#include <vector> // std::vector
#include <numeric> // std::sort, std::accumulate
#include <cassert> // assert
auto score(std::vector<double> scores) {
assert(scores.size()>2);
auto n = scores.size() - 2;
// sort ...
// sum ...
return sum / n;
}
int main() {
assert(score({1,5,9}) == 5);
assert(score({5,5,5}) == 5);
assert(score({0,5,0}) == 0);
assert(score({1,2,3,4,5,6}) == 3);
}
I left the actual implementation for you. My implementation fits in three lines.
I hope this inspires you to get a clean implemntation, that you can easily use to write the rest of the program with.
As the title suggests, my program which is designed to find the largest element within a user defined integer array becomes unstable when all negative numbers are used for the user input. Additionally the output becomes unstable when all zero's are used for the user input (excluding the input for total # of elements).
The program works just fine when all positive numbers are used. This is quite perplexing to me and I'm sure there's a valid explanation but I was under the impression that in C++, the int & float data types were automatically signed and would be able to handle negative numbers for it's data range. So why would the program not return a valid output if all negative numbers are used for the user array input(s)?
Bad Output:
Please enter a total number of elements you'll be using: 5
Please enter each variable one by one.
Enter number 1: -10
Enter number 2: -5
Enter number 3: -20
Enter number 4: -2
Enter number 5: -7
The largest element within specified realNum[5] array is element number: 6 with a value of: 5.88501e-039
Good Output:
Please enter a total number of elements you'll be using: 5
Please enter each variable one by one.
Enter number 1: 10
Enter number 2: 5
Enter number 3: 20
Enter number 4: 2
Enter number 5: 7
The largest element within specififed realNum[5] array is element number: 3 with a value of: 20
Program:
//10.2 Largest Element Finder of an Array
//Mandatory header
#include <iostream>
//Use namespace std ;
using namespace std ;
//Mandatory main method
int main ()
{
//Declare and initlize variables
int i, total, realNum = 0, temp = 1 ;
//Ask user to input a number of total elements
cout << endl << endl
<< "Please enter a total number of elements you'll be using: " ;
//Wait for user input
cin >> total ;
//Declare array set
float setNum [total] ;
//Ask user to input each varaible
cout << endl
<< "Please enter each variable one by one." << endl << endl ;
for ( i = 0 ; i < total ; i ++ )
{
cout << endl << "Enter number " << (i + 1) << ": " ;
cin >> setNum [i] ;
}
//Find the largest element within the array
for ( i = 0 ; i < total ; i ++ )
{
if ( setNum [i] <= setNum [temp] ) //Discard current i if less than the next element - Means temp is HIGHER and should be saved
{
if ( setNum [temp] >= setNum[realNum] )
realNum = temp ; //Temp can now be changed for iteration purposes as realNum is saving the highest element's positon
}
else if ( setNum [i] >= setNum [temp] ) //Discard current i if more than the next element and use the remainder to compete against the realNum
{
if ( setNum [i] >= setNum [realNum] )
realNum = i ;
}
i ++ ;
temp += 2 ;
}
//Display calculations
cout << endl << endl
<< "The largest element within specififed realNum[" << total << "] array is element number: " << (realNum + 1) << " with a value of: " << setNum[realNum] << endl ;
//Mandatory return statement
return 0 ;
}
I am writing code for an assignment that wants me to make a program that asks the user for the amount of integers they'd like to input then it accepts each input while testing if the value is the max value or the minimum.
The program runs fine but for some reason will stop and show me the min and max number when I have entered in 1 integer less than the original input.
Examples of the problem I am having:
If I input 5 for the first value, it asks me to enter 5 integers.
After entering 4 numbers, 1 2 3 and 4.
It tells me the max is 4 and min is 1.
It prevents me from entering in the 5th integer.
Additionally,
If I input 5 for the first value, it asks me to enter 5 integers.
If I enter a negative number, like -1, the input allowed to me is further
shortened.
If I enter -1, 2, 3 then the output is min: 2 and max: 3
I have two main questions:
What adjustments do I need to make to my code so that I can properly
enter in the number of integers initially asked for?
What adjustments need to be made in order for me to be able to enter
negative integers so they are outputted correctly?
The code:
#include <iostream>
using namespace std;
int main()
{
int input;
int tmp;
int counter = 1;
int max_num = 0;
int min_num;
// prompt user for integer amount
cout << "How many integers would you like to enter? " << endl;
cin >> input;
cout << "Please enter " << input << " integers." << endl;
tmp = input;
// loop for requested amount with a test for each input
while (counter <= tmp) {
cin >> input;
// if smaller than previous number it is the minimum
if (input < min_num || min_num == -1) {
min_num = input;
counter++;
}
// if larger than previous number it becomes max number else
if (input > max_num) {
max_num = input;
counter++;
} else { // continue loop if number isn't bigger than max or smaller than min
counter++;
}
}
// display the max and min
cout << "min: " << min_num << endl;
cout << "max: " << max_num << endl;
return 0;
}
In a population, the birth rate is the percentage increase of the population due to births, and the death rate is the percentage decrease of the population due to deaths. Write a program that asks for the following:
The starting size of a population (minimum 2) (Prompt Enter starting size:)
The annual birth rate (Prompt Enter annual birth rate:)
The annual death rate (Prompt Enter annual death rate:)
The number of years to display (minimum 1) (Prompt Enter years to display:)
The program should then display the starting population and the projected population at the end of each year. It should use a function that calculates and returns the projected new size of the population after a year. The formula is
N = P(1 + B)(1 - D)
where N is the new population size, P is the previous population size, B is the birth rate, and D is the death rate. Annual birth rate and death rate are the typical numbers of births and deaths in a year per 1000 people, expressed as a decimal.
So, for example, if there are normally about 32 births and 26 deaths per 1000 people in a given population, the birth rate would be .032 and the death rate would be .026.
Here is my code; I am having trouble figuring out how to do the calculation.
#include "stdafx.h" // Defines IDE required "pre-compiled" definition files
#include <iomanip>
#include <iostream>
using namespace std
int main ()
{
double startPop, // To hold the starting population.
float birthRate, // To hold the birth rate.
float deathRate; // To hold the death rate.
int numYears; // To hold the number of years to track population changes.
// Input and validate starting population
cout << "This program calculates population change.\n";
cout << "Enter the starting population size: ";
cin >> startPop;
while (startPop < 2.0)
{
cout << "Starting population must be 2 or more. Please re-enter: ";
cin >> startPop;
}
// Input and validate annual birth and death rates
cout << "Enter the annual birth rate (as % of current population): ";
cin >> birthRate;
while (birthRate < 0)
{
cout << "Birth rate percent cannot be negative. Please re-enter: ";
cin >> birthRate;
}
birthRate = birthRate / 100; // Convert from % to decimal.
cout << "Enter the annual death rate (as % of current population): ";
cin >> deathRate;
while (deathRate < 0)
{
cout << "Death rate percent cannot be negative. Please re-enter: ";
cin >> deathRate;
}
deathRate = deathRate / 100; // Convert from % to decimal.
cout << "For how many years do you wish to view population changes? ";
cin >> numYears;
while (numYears < 1)
{
cout << "Years must be one or more. Please re-enter: ";
cin >> numYears;
population = projectedNewSize(populationStartingSize, annualBirthRate, annualDeathRate);
cout << population << endl;
populationStartingSize = population;
}
printPopulations(startPop, birthRate, deathRate, numYears);
return 0;
} // End of main function
You can do this recursively or using a simple for loop.
E.g. Say if the numYears = 10, you would want to loop 10 times.
Create a temporary variable before your for loop and assign it the value of your startPop, e.g. endPop.
Then, starting with an initial population size of endPop, and death rate of deathRate as well as birth rate of birthRate, you calculate the population size after one year.
Having computed the population after one year in the first loop, you update endPop with the new value.
Subsequently, in the second loop, you use endPop once again as the new starting population size and the cycle repeats itself up till the end of your for loop, i.e. when 10 years have passed.
You did not declare the variable population in the above code snippet before using it.
Implementation:
while (numYears < 1)
{
cout << "Years must be one or more. Please re-enter: ";
cin >> numYears;
}
double population = populationStartingSize;
for ( int i = 0; i < numYears; i++) {
population = projectedNewSize(population, annualBirthRate, annualDeathRate);
cout << "After " << i+1 << "years: " << population << endl;
}
}
Take note that there is chance of over- and under-flow if your number gets too small or too big.
Implementation:
double projectedNewSize(double populationStartingSize, float annualBirthRate, float annualDeathRate) {
return populationStartingSize * (1 + annualBirthRate) * (1 - annualDeathRate);
}
For reading of numYears, you could consider using a do-while loop, :p.
I am writing a program for a homework assignment that calculates rental car rates based on make, days rented and miles driven. Overall the program works except, when the user is prompted for the number of cars to be calculated, the program continues to prompt the user for input after the number has been exceeded. Also, the formatting for the miles is correct for the first vehicle entered but changes for subsequent entries.
Any help with these two issues would be greatly appreciated!
Code:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
// Change the console's background color.
system ("color F0");
// Declare the variables.
char carType;
string brand, f("Ford"), c("Chevrolet");
int counter = 0, cars = 0;
double days, miles, cost_Day, cost_Miles, day_Total;
cout << "Enter the number of cars you wish to enter: ";
cin >> cars;
cin.ignore();
while (counter <= cars)
{
cout << "Enter the car type (F or C): ";
cin >> carType;
cin.ignore();
cout << "Enter the number of days rented: ";
cin >> days;
cin.ignore();
cout << "Enter the number of miles driven: ";
cin >> miles;
cin.ignore();
if (carType == 'F' || carType == 'f')
{
cost_Day = days * 40;
cost_Miles = miles * .35;
day_Total = cost_Miles + cost_Day;
brand = f;
}
else
{
cost_Day = days * 35;
cost_Miles = miles * .29;
day_Total = cost_Miles + cost_Day;
brand = c;
}
cout << "\nCar Days Miles Cost\n";
cout << left << setw(12) << brand << right << setw(6) << days << right << setw(8) << miles
<< fixed << showpoint << setprecision (2) << setw(8) << right << "$" << day_Total << "\n\n";
counter++;
}
system ("pause");
}
You have started counting from 0 int counter = 0, cars = 0;
You then count until you are equal to the number that was entered (the "or equal to" bit of while (counter <= cars)).
As a worked example, if I want 3 entries:
Start: counter = 0, cars = 3.
0 <= 3: true
End of first iteration: counter = 1
1 <= 3: true
End of second iteration: counter = 2
2 <= 3: true
End of third iteration: counter = 3
3 <= 3: true (the "or equal" part of this)
End of FORTH iteration: counter = 4
4 <= 3: false -> Stop
We have completed 4 iterations instead of 3. If we only checked for "strictly less than" (counter < cars), the condition at the end of the third iteration would be false, and we'd have ended there.
The heading of your while loop should be:
while(counter < cars)
rather than
while(counter <= cars)