Every time I run the program, using the exact same values (25 for diameter and 5 for depth), I am getting different values for water_price and I'm not sure why.
Some of the outcomes:
$6.62256e+07 is the total cost.
$0 is the total cost.
$2.43411e-27 is the total cost.
I don't know if I am dealing with values in memory not playing well with each other, not flushing or what.
Why are the outcomes different every time I run this program?
#include <iostream>
#define PI 3.1416
#define WATER_COST 1.80
using std::cout;
using std::cin;
using std::endl;
int main() {
float pool_diameter, pool_depth;
float pool_radius = pool_diameter / 2;
float pool_volume_sq_inches = (PI * pool_radius * pool_radius * pool_depth) * 1728;
float pool_gallons = pool_volume_sq_inches / 231;
float water_price = (pool_gallons / 748) * WATER_COST;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
cout << "\n$" << water_price << " is the total cost." << endl;
return 0;
}
See how we need to declare the variables to begin with, then when you ask for input it will be stored in those variables, and then you can continue on with the calculations you need.
#include <iostream>
#define PI 3.1416
#define WATER_COST 1.80
using std::cout;
using std::cin;
using std::endl;
int main() {
float pool_diameter = 0.0;
float pool_depth = 0.0;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
float pool_radius = pool_diameter / 2;
float pool_volume_sq_inches = (PI * pool_radius * pool_radius * pool_depth) * 1728;
float pool_gallons = pool_volume_sq_inches / 231;
float water_price = (pool_gallons / 748) * WATER_COST;
cout << "\n$" << water_price << " is the total cost." << endl;
return 0;
}
You may want to get the inputs soon after the declaration.
float pool_diameter, pool_depth;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
Rest code would work the way it is.
A good practice would be to initialize your variables like Omid-CompSci has answered here.
Statement float pool_radius = pool_diameter / 2; is executed before
cin >> pool_diameter;. Default value(garbage value) is used every time to calculate the pool_radius that is reason for different values in different runs.
change the order.
Related
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 4 years ago.
Improve this question
Just begin to learn C++, and the code below can't return the right value. I can't find out where is wrong, need some help here, thank you!
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Enter the height in CM: ";
cin >> CM;
cout << "Your in M is " << M << endl;
return 0;
}
cin operation is when you retrieve the value:
you need to get it before any process:
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
cout << "Enter the height in CM: ";
cin >> CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
return 0;
}
Just for the fun of it, and for education's sake. If you want to emulate declarative programming in C++, to define the relationship between variables and "get the updated value" afterwards, you can get by with a lambda.
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
auto M = [&] { return 1.0f * CM / CM2M + (CM % CM2M) * 0.01f; };
cout << "Enter the height in CM: ";
cin >> CM;
cout << "Your in M is " << M() << endl;
return 0;
}
It's cheating really, since M() invokes the lambda, thus making sure the arithmetic is done after the value is known. Writing the operations in the correct sequence is far clearer. C++ also allows you to declare variables right at the first point of use, so you don't need to declare all your variables ahead of time, you can execute code before the declaration is needed. So you'd do something like this:
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
cout << "Enter the height in CM: ";
cin >> CM;
float M = 1.0f * CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
return 0;
}
I added the artificial 1.0f to make sure it doesn't do integer division, which was another bug in your code.
Put the "float M=..." line after the "cin >>CM;" line. Now you are trying to compute the number of meters before the number of centimeters is even entered, so of course the result is random.
Because CM is only declared and used in the equation before the user has a chance to initialize it.
The current program flow is like this:
CM is declared
M is calculated using the CM value (whatever that is at this moment)
The user enters value for CM
The user sees the result of the conversion (the value for M) however it is already calculated and the user input is not actually
used.
To fix the program move the calculation after the user input:
cout << "Enter the height in CM: ";
cin >> CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
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
So, writing my first program! Any hints about the errors above will be appreciate!! :)
I'm getting mismatch formal parameter list and unable to resolve function overload.
many many thanks,
#include <iostream>
#include <cmath>
#include "COMPFUN.H"
using namespace std;
int main()
{
double futureValue = 0.0;
double presentValue = 0.0;
double interestRate = 0.0;
cout << "Please enter Present Value: ";
cin >> presentValue;
cout << "Please enter rate: ";
cin >> interestRate;
futureValue = ( presentValue * 1 + interestRate / 1200.0 , 36) << endl;
cout << "Future value is: " << futureValue << endl;
system("pause");
return 0;
}
What do you expect the
futureValue = ( presentValue * 1 + interestRate / 1200.0 , 36) << endl;
endl to do at the end of this line? Do you want to shift the result by endl bits? Do you want a \n appended to futureValue and have it flushed afterwards?
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.
I am trying to make a program which does a very basic calculation, but for some reason i can't get the code right. It is supposed to calculate the miles per gallon for one trip. You can then add this info multiple times (for different trips) and for each time it should calculate the total miles per gallon (i.e. the average miles per gallon of all the trips). This is the code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int counter = 1;
double milePerRe, milePerTo = 0, x, y;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
cout << "Enter gallons: ";
cin >> y;
while (x != -1)
{
milePerRe = x/y;
milePerTo += milePerRe;
milePerTo /= counter;
cout << "MPG this tankful: " << setprecision( 6 ) << fixed << milePerRe;
cout << "\nTotal MPG: " << setprecision( 6 ) << fixed << milePerTo << endl << endl;
counter++;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
if (x != -1)
{
cout << "Enter gallons: ";
cin >> y;
}
}
system("pause");
return 0;
}
When I run the program and say I enter 10 on the miles and 1 on the number of gallons the first time and the second time, everything works fine. Then if i do it again a third time the calculations begin to become incorrect.
You can not calculate average of averages the way you do it. In your code you are dividing by the counter EACH iteration, while you should divide it only at the end.
Best way to do what you need is something like this:
...
double totalMiles = 0;
double totalGallons = 0;
...
while (x != -1)
{
milePerRe = x/y;
totalMiles += x;
totalGallons += y;
milesPerTo = totalMiles / totalGallons;
...
However, if your task was to explicitly calculate the average of trips (not the average of miles/gallons), you would need to introduce another variable, like this:
...
double currentMilesPerTo;
...
while (x != -1)
{
milePerRe = x/y;
milePerTo += milePerRe;
currentMilesPerTo = milePerTo/counter;
....
cout << "\nTotal MPG: " << currentMilesPerTo;
...
the value of x and y are not being updated properly i guess.after every iteration try to make x and y to zero.
hope it works this way
TNQ