So I'm just getting introduced to programming, and I have to say that this is the single most rewarding yet frustrating thing I've ever done. I'm taking on projects of increasing difficulty, the most recent of which involves the use of the Monte Carlo method and plenty of loops. The following is the code that is completed so far:
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>
#include <ctime>
using namespace std;
int main ()
{
srand (time(0));
string operation;
cout << "Using the letters 'o', or 'q', please indicate if you would like to simulate once, or quit the program: " << endl;
cin >> operation;
string reservoir_name; // Creating variables for reservoir
double reservoir_capacity;
double outflow;
double inflow_min;
double inflow_max;
if (operation == "q")
{
cout << "Exiting program." << endl;
system ("pause");
return 0;
}
while (operation == "o") // Choose one or multiple simulations.
{
string reservoir_name; // Creating variables for reservoir function
double reservoir_capacity;
double inflow_min = 0;
double inflow_max = 0;
double inflow_range = inflow_min + inflow_max;
double inflow_difference = inflow_max - inflow_min;
double inflow_threshold = .9 * inflow_range/2; // Math for acceptable flow threshold.
cout << "What is the name of the reservoir?" << endl;
cin.ignore ();
getline (cin,reservoir_name); // Grab whole string for reservoir name.
cout << "What is the capacity of the reservoir in MAF (Millions of Acre Feet)?" << endl;
cin >> reservoir_capacity;
cout << "What is the minimum inflow?" << endl;
cin >> inflow_min;
cout << "What is the maximum inflow?" << endl;
cin >> inflow_max;
cout << "What is the required outflow?" << endl;
cin >> outflow;
inflow_range = inflow_min + inflow_max;
inflow_threshold = .9 * inflow_range/2;
cin.ignore ();
if (outflow > inflow_threshold) // Check for unacceptable outflow levels.
{
cout << "Warning! The outflow is over 90% of the average inflow. Simulation aborted. Returning to main menu." << endl;
}
else
{
const int number_simulations = 10;
double fill_level = 0;
int years = 1;
cout << "Running simulation." << endl;
for (int i = 1; i < number_simulations; i++) // Each year
{
for (years; fill_level < reservoir_capacity; years++ )
{
double r = rand() * 1.0 / RAND_MAX;
double x = inflow_min + inflow_range * r;// SHOULD be between minimum inflow and maximum inflow.
if (fill_level < 0)
{
fill_level = 0;
}
} // Simulate the change of water level.
cout << years << endl;
}
}
cout << "What would you like to do now?" << endl; // Saving for later. The menu re-prompt message and code.
cout << "Using the letters 'o', or 'q', please indicate if you would like to simulate once, or quit the program: " << endl;
cin >> operation;
}
system ("pause");
return 0;
}
So I suppose my main question is I'm running into a wall concerning setting up the for loops underneath "Running simulation" where I need to set up the first for loop to run the internal for loop 10 times, with each of those 10 iterations of the internal for loop coming up with random numbers for the range of acceptable results from the query for a random value. I've been told that the idea is to use the Monte Carlo method, i.e.
double r = rand() * 1.0 / RAND_MAX;
double x = inflow_min + inflow_range * r;// SHOULD be between minimum inflow and maximum inflow.
so the program will create a random value for the inflow. The idea is that the internal for loop will continue to run until the fill_level of the reservoir, which starts at 0, hits the reservoir_capacity. The process of simulating how many years (each iteration of the internal for loop representing a year) is to be repeated 10 times by the parent for loop of the fill_level simulation for loop.
When I try to run the program as you see it here, it will go all the way up until the "Running simulation" and then it won't proceed any further. Does someone more experienced than myself understand what I'm saying and know what is happening?
for (years; fill_level < reservoir_capacity; years++ )
{
double r = rand() * 1.0 / RAND_MAX;
double x = inflow_min + inflow_range * r;// SHOULD be between minimum inflow and maximum inflow.
if (fill_level < 0)
{
fill_level = 0;
}
} // Simulate the change of water level.
You never increase fill_level in this loop. It's an infinite loop.
Related
I'm trying to write a program that reads in positive float numbers from the user and then when the user's is a negative number, gives the average of the numbers, excluding the negative.
#include <iostream>
using namespace std;
int main() {
float av_number, total = 0, input;
do {
for (int i = 1; i >= 1; i = ++i) {
cout << "Please input a number: ";
cin >> input;
total = total += input;
av_number = total / i;
cout << av_number << endl;
break;
}
} while (input >= 0);
cout << av_number << endl;
}
When I run this, the program simply adds the inputs together on each line, and then subtracts my final negative input before closing the program.
If I were to guess, It's likely a logical confliction within my sequence of do & for loops, but I'm unable to identify the issue. I may have also misused i in some fashion, but I'm not certain precisely how.
Any help would be appreciated as I'm still learning, Cheers!
you don't need the for loop, you just need some iterator to count the number of entered numbers, so you can delete that for loop and use a counter variable instead.
also, you are breaking in the loop without checking if the input < 0, so you can write this
if (input < 0)
break;
also, you shouldn't calculate av_number = total / counter; except only after the end of the big while loop
it's total += input; not total = total += input;
writing while (input >= 0) wouldn't make sense as long as you are breaking inside the loop when input < 0, so you can write while (true); instead
and this is the code edited:
#include <iostream>
using namespace std;
int main() {
float av_number = 1.0, total = 1, input = 1.0;
int counter = 0;
do {
cout << "Please input a number: ";
cin >> input;
if (input < 0)
break;
counter++;
total += input;
} while (true);
av_number = total / counter;
cout << av_number << endl;
}
and this is the output:
Please input a number: 5
Please input a number: 12
Please input a number: 7
Please input a number: -2
8
P.S : read more about Why is "using namespace std;" considered bad practice?
You should move the calculation of the average value out of the loop where the adding takes place and only add non-negative values to total.
#include <iostream>
int main() {
float total = 0.f;
int i = 0;
// loop for as long as the user successfully enters a non-negative value:
for (float input; std::cout << "Please input a number: " &&
std::cin >> input &&
!(input < 0.f); ++i)
{
// now `input` is non-negative
total += input; // and only sum it up here, no average calculation
}
if (i > 0) { // avoid division by zero
// finally calculate the average:
float av_number = total / i;
std::cout << av_number << '\n';
}
}
The condition for the loop is that std::cout << "Please input a number: " succeeds and that std::cin >> input succeeds and that input is not less than zero.
I am new to C++.
Below is code that lets a user enter five elements into an array, then sums those values, and obtains the mean and a predicted future value.
The code works fine if the user enters five elements, but how do I handle the situation in which one or more values are missing?
I have written code further below that seems to solve this problem, by defining a missing value to be a negative number. That code also seems to work fine. But, is there a better, accepted way of handling missing values in a C++ array?
If I try to run the first code in Microsoft Visual Studio 2019, I do not even know what to enter for a missing value. If I do not enter anything, and just press the Enter key, nothing happens.
Here is the original code that works with five elements. This code is slightly modified from code written by Saldina Nurak:
#include <iostream>
using namespace std;
int nmonths = 6;
int totalmonths = 24;
int main()
{
// {100, 220, 300, 0, 200, 250}
// This line works in the command window
// float monthArray[nmonths];
// for Microsoft Visual Studio 2019
float monthArray[6];
float total = 0;
for(int i = 0; i <= (nmonths-1); i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> monthArray[i];
total += monthArray[i];
}
float average = total / nmonths;
float inTwoYears = average * totalmonths;
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
Enter Amount 1: 100
Enter Amount 2: 220
Enter Amount 3: 300
Enter Amount 4: 0
Enter Amount 5: 200
Enter Amount 6: 250
total = 1070
average = 178.333
inTwoYears = 4280
Here is the modified code I wrote that seems to handle missing values, by defining them to be negative numbers:
#include <iostream>
using namespace std;
int nmonths = 6;
int totalmonths = 24;
int emptycounter = 0;
int main()
{
// This works from the command window
// float monthArray[nmonths]; // {100, 220, 300, 0, -99, 250};
// for Microsoft Visual Studio I have to use
float monthArray[6];
float total = 0;
for(int i = 0; i <= (nmonths-1); i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> monthArray[i];
if (monthArray[i] >= 0) emptycounter++;
else (emptycounter = emptycounter);
if (monthArray[i] >= 0) total += monthArray[i];
else total = total;
}
float average = total / emptycounter;
float inTwoYears = average * (totalmonths - (nmonths - emptycounter));
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
C:\Users\mark_>cd C:\Users\mark_\myCppprograms
C:\Users\mark_\myCppprograms>c++ MissingDataInArray2.cpp -o MissingDataInArray2.exe -std=gnu++11
C:\Users\mark_\myCppprograms>MissingDataInArray2
Enter Amount 1: 100
Enter Amount 2: 220
Enter Amount 3: 300
Enter Amount 4: 0
Enter Amount 5: -99
Enter Amount 6: 250
total = 870
average = 174
inTwoYears = 4002
What is the standard approach for dealing with missing values in C++ and how does a user enter a missing value from the keyboard?
You would have to define what is supposed to be a missing value if you are trying to read as a number. You could maybe read the line and try to parse it to a int and if unable to parse then it would be your missing value?
Also, you are not using C++ arrays, you are using C arrays.
C++ has an array container but vector gives you much more flexibility.
You could do something like this:
vector<int> monthArray;
int value;
for(int i = 0; i < nmonths; i++) // See the change done in the test
{
cin >> value;
if(value > 0)
monthArray.push_back(value); // This would insert at the end and take care of resizing the container as needed.
}
monthArray.size(); // This returns how many elements you have in the container
Both your else clauses are assigning a variable to itself. You can erase both and put the 2 statements inside the same if:
if (monthArray[i] >= 0)
{
emptycounter++;
total += monthArray[i];
}
But if you use vector you won't need emptycounter. The size of the vector will contain the number of valid elements.
for(int i = 0; i < nmonths; i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> value;
if(value > 0)
{
monthArray.push_back(value);
total += value;
}
}
After all that... There is this question: Do you really need an array? You just seem to accumulate the valid values and never refer to the array after saving the elements on it.
P.S: to use vector you need to #include<vector>
What is the standard approach for dealing with missing values in C++ ?
std::optional is standard and serves the need.
How does a user enter a missing value from the keyboard?
There is no definition of operator>> for istream and std::optional<float> but you can write a function that behaves the way you want.
For example you could use std::getline to always read an entire line, then if the line is blank return an empty std::optional<float> and if not then parse the number and return a std::optional<float> that contains it.
Here is code that implements the answer from #vmp when missing observations are defined as NA (as in R and suggested by #Yksisarvinen in a comment) by using stoi. I have not yet figured out how to implement the answer from #Ben Voigt.
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int nmonths = 6 ;
int totalmonths = 24 ;
int main()
{
float total = 0;
vector<int> monthArray;
string value;
for(int i = 0; i < nmonths; i++)
{
cout << "Enter Amount " << i+1 << ": ";
cin >> value;
if(value != "NA")
{
monthArray.push_back(stoi(value));
total += stoi(value);
}
}
float average = total / monthArray.size() ;
float inTwoYears = average * (totalmonths - (nmonths - monthArray.size())) ;
cout << "total = " << total << endl;
cout << "average = " << average << endl;
cout << "inTwoYears = " << inTwoYears << endl;
}
// C:\Users\mark_>cd C:\Users\mark_\myCppprograms
// C:\Users\mark_\myCppprograms>c++ vector2.cpp -o vector2.exe -std=gnu++11
// C:\Users\mark_\myCppprograms>vector2
// Enter Amount 1: 100
// Enter Amount 2: 220
// Enter Amount 3: 300
// Enter Amount 4: 0
// Enter Amount 5: NA
// Enter Amount 6: 250
// total = 870
// average = 174
// inTwoYears = 4002
I am trying to get this 'do while' loop to run 3 times and then display the amount in the accumulator contain within a while loop inside the 'do while' loop.
It seems to be counting correctly, but only runs the while loop on the first. When run, instead of going on to ask for the next set of numbers, it just displays the first batch (added up correctly). I have tried switching some of the code around and searching google, but can't find the answer.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int storeNum = 1;
int payRollAmount = 0;
int totalPayroll = 0;
do
{
cout << "Store " << storeNum << ":" << endl;
while (payRollAmount <= -1)
{
cout << "Enter Store's Payroll Amount (-1 to exit): ";
cin >> payRollAmount;
totalPayroll += payRollAmount;
}
storeNum++;
} while (storeNum <= 3);
cout << "The Total Payroll is: " << totalPayroll << endl;
system("pause");
return 0;
}
The code should take in an unknown amount of "payrolls," allow you to exit using -1, and then continue on to the next stores payrolls. It should do this 3 times, and then display the total amount (all numbers entered added together.
Hi perhaps reset payRollAmount at each iteration? That way it will continue to request the input.
for (int amount = 0; amount != -1; ) {
cout << "Enter Store's Payroll Amount (-1 to exit): ";
cin >> amount;
totalPayroll += amount;
}
In one of my c++ class assignments, I was given the task:
Write a program that reads in a list of floating-point numbers and then prints out the count of the values, the average, and the standard deviation.
You can assume that the the user's input is always valid and that the list contains at least two numbers.
You can assume that the numbers in the list are separated by one space character and that the character following the last number in the list is the newline character.
Implement a loop in which the above actions are repeated until the user requests to quit.
I am struggling with the last step, where I need to ask the user if they want to continue. My code is as follow.
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
char counter;
do {
char ch = ' ';
int i = 0;
double sum = 0;
double average = 0;
double sum_squared = 0;
cout << "Please enter a list of values (of type double): ";
do {
double x;
cin >> x;
ch = cin.get();
i += 1;
sum += x;
double x_squared = pow(x, 2);
sum_squared += x_squared;
} while (ch != '\n');
average = sum / i;
double standard_deviation = sqrt((sum_squared - (pow(sum, 2) / i)) / (i - 1));
cout << "Number = " << i << endl;
cout << "Average = " << average << endl;
cout << "Standard deviation = " << standard_deviation << endl;
cout << "Continue? (y,n) "; cin >> counter;
} while (counter = 'y');
return 0;
}
I was expecting that when user enter y in the end, the program would re-execute. But it turned out to be weird. When I enter n, the code still re-execute. Can anyone explain why? Additionally, how do I correctly implement this function to my code? Thank you all for your help and response.
changing
counter = 'y'
to
counter == 'y'
near the end will yield the satisfactory result.
I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100