I'm Having problems with to of the questions on my C++ homework.
Write a program to analyze gasoline price in the past 10 days. First, ask the user to enter the prices. Then do the following:
(a) Calculate and display the average price in the first 5 days and the average price in the second 5 days
(b) Compare the two average prices. Determine and report which one is higher (or they are the same).
(c) Compare each day’s price (except day 1) with the price the day before. Determine whether it became higher, lower or remained the same. Count and report the number of days the price was higher than, lower than and the same as the price the day before, respectively.
i'm not sure how to compare how to compare the first five days with the last five days, and part c I'm completely lost on....
i'm not looking for someone to do my homework for me, but a push in the right direction would be a great help!
here is what I have made so far:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
double gasPrice[10];
double firstFive = 0.0;
double lastFive = 0.0;
double ffAvg = 0.0;
double lfAvg = 0.0;
for (int x = 0; x < 10; x = x + 1)
{
gasPrice[x] = 0.0;
}
cout << "You will be asked to enter daily gas prices for 10 days."<< endl;
ofstream gasprice;
gasprice.open("gasprice.txt", ios::app);
if (gasprice.is_open())
{
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter the gas price " << x+1 << ": ";
getline(cin, gasPrice[x];
}
if ( ffAvg > lfAvg)
{
cout << "The first five days have a lower gas price " << ffAvg << lfAvg << endl;
}
else if ( ffAvg < lfAvg)
{
cout << "The last five days have a lower gas price " << ffAvg << lfAvg << endl;
}
system("pause ");
return 0;
}
Read the requirements like they are a description rather than a computer formula. It can become overwhelming when learning something for the first time and we get drowned by the things that would come natural in another environment.
Anyway, you are not to compare the days individually but an AVERAGE of the days. So you first need to compute the AVERAGE of the first five and the AVERAGE of the second five days, then compare that.
For the second part of your question, aggregators for your totals is the push I would give you.
Hope this helps.
Break down the problem in to a series of stages: Firstly, you need to get 10 input prices from the user, and store them in an array of size 10.
Next, you need to compute the average price for the first five days (i.e. for values in index 0-4 of your array), and store it in ffAvg, you can do this using the following simple for loop:
double sum;
for( int i = 0; i < 5; i++ )
{
sum += gasPrice[i];
}
double ffAvg = sum / 5;
You then do this with the 2nd 5 days, storing the average in lfAvg.
The next part of your task is to compare the averages, you can doing this using if and else if statements, for example, if you wanted to compare to numbers, num1 and num2 you might do the following:
if( num1 > num2 )
{ /* Do something */ }
This will compare num1 and num2 and if num1 is greater than num2 it will perform the code in the braces.
To do the last comparison you simply combine what we have done above on a per day basis. Try to experiment with various ways of doing it, as this will help you to learn more.
Hope this helps you! :)
EDIT: I also noticed that you've not closed a lot of your bracers, you must always do this so the compiler can work properly. Every { must have a corresponding }, else the compiler should throw up errors, and not compile.
I sugest doing as following:
double average1=0.0;
for(int i=0;i<5;++i) {
average1 += values[i];
}
average1/=5.0;
double average2=0.0;
for(int i=5;i<10;++i) {
average2 += values[i];
}
average2/=5.0;
Also, take a look at std::vector, it may help you in further exercises:
http://www.cplusplus.com/reference/stl/vector/
You should first compute the average of the first and last 5 days. The average is defined by the sum divided by the number of items. So your average will be (gasPrice[0] + gasPrice[1] + gasPrice[2] + gasPrice[3] + gasPrice[4]) / 5.0.
You should probably make this computation in a loop similar to the one you have for getting the input. The loop should only iterate 5 times.
Related
I'm new to coding and am having trouble with one of my first projects.
So I have to basically type a number and then have that number spit out some answers involving things like addition and multiplication. (ex. if I put in 5, one of the answers is to simply multiply that 5 by 30. Or another adds it).
The issue is that the only way I can get that number to be different and give the corresponding answers is if I go into the code and change the integer assigned to the variable, which is pretty counterintuitive.
I've tried deleting the variable, setting = 0, moving it around; nothing is working.
stocks = 0;
investment = stocks * 30;
charges = investment * .015;
total = charges + investment;
cout << "Cindy, how much are you investing?";
cin >> stocks;
cout << endl;
some of the code there. Line in question is the "stocks = 0;" one. After that, it's the other variables that would be output with their associated variables. Any help would be appreciated, I hope this makes sense for what I'm asking! Thanks in advance
You will have to cin the number.
#include <iostream>
int main() {
int stocks;
std::cout << "Cindy, how much are you investing?";
std::cin >> stocks;
investment = stocks * 30;
charges = investment * .015;
total = charges + investment;
std::cout << "The total charges would be " << total << "." << std::endl;
}
I have a program that can generate a random integer every 1/10 second.
Here is the code:
int main()
{
ofstream myfile;
int max;
cout << "Max number: ";
cin >> max;
for (int i = 0; i < max; ++i)
{
myfile.open("test.txt",fstream::app);
myfile << random_int() << "\n";
myfile.close();
this_thread::sleep_for(chrono::milliseconds(100));
}
return 0;
}
int random_int()
{
return rand() % 10;
}
Now the question is, I need to write a program that calculate then output the average in the same rate. If the output of the number generator is:
1
2
3
4
5
The output of the average calculator should be
1
1
2
2
3
Every 1/10 second the program will output a number.
Note: The max number could be from 0 to couple millions. Calculating the average by adding all previous number during the time interval won't be ideal.
I am a sophomore student and a research assistant in a university. This is a simplified version of a problem that I encounter currently. Any suggestion will be greatly appreciated.
Update: Thanks for the help from Fei Xiang and oklar. Yes, remember the previous sum is the only way to make the calculation in time. However, since the random generator output file is changing constantly and the new output is appended to the old outputs, I am not sure how to get the most current data efficiently.
You don't need to calculate all the numbers that has been added each time, you only need to add the last one to a sum variable and divide by the amount of generated numbers.
Say you have:
1
2
3
4
5
Sum variable is 15. If you divide by the amount of numbers which is 5, you'll get the expected output of 3. Continuing, add the number 9 for instance to the sum variable and divide by the amount of generated numbers 6, you'll end up with an average of 4.
The i in your for loop can be used as a counter for the amount of generated numbers. Pseudo code:
sum += randomInt();
avg = sum/i;
EDIT:
I see that you are opening and closing the file each time in the for loop in your post. This can be done outside the loop, which will speed things up. If I understand you correctly, your mission is to generate a random number then calculate the average from the previous numbers and finally append it to the text file? If so, you're on point.
int i_random;
int avg;
int sum = 0;
myfile.open("avg.txt",fstream::app);
for (int i = 1; i < max + 1; ++i)
{
i_random = random_int();
sum += i_random;
avg = sum/i;
myfile << avg << "\n";
this_thread::sleep_for(chrono::milliseconds(100));
}
myfile.close();
See http://www.cplusplus.com/doc/tutorial/files/ for other operators. Check out cppreference for seek and tell if you want to skip to a position in the file.
In your program, you will have the user enter what percentage improvement in
rocket speeds (up to but not exceeding light speed!) each year. Your program will
then ask the user the maximum number of years that they are willing to wait on
earth before they leave. Use while loops in this step to implement simple error
checking by asking the user repeatedly until they give a valid input. Percentage
must be somewhere between 0 and 100 and the years waiting must be a positive
integer.
Next, your program will generate a table using a for loop. That table will have
four columns with one row for leaving immediately followed by one row for each
year the user is willing to wait. The first column will contain the departure year.
The second column contains the rocket speed that rockets will be able to achieve
that year. The new rocket speed each year is calculated with this equation:
velocity = velocity + (lightspeed - velocity) * (improvement/100)
I was able to correctly print out each year in the table I am trying to make, but I am having trouble figuring out how to use a loop to find the speed of the rocket for each year using a loop. I am pretty sure I am supposed to use a nested for loop, but with the code I have right now, it is stuck in an infinite loop. Any guidance in the right direction would be appreciated!
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main()
{
int percentIncrease = 0;
int maxYears = -1;
float speedLight = 299792;
while((percentIncrease <= 0) || (percentIncrease >= 100))
{
cout << "What percentage do rocket speeds increase by each year?" << endl;
cin >> percentIncrease;
}
while(maxYears < 0)
{
cout << "What is the maximum number of years you are willing to wait on
earth before you leave?" << endl;
cin >> maxYears;
}
cout << "Start year|\tAvg Speed|\tEarth ETA|\tYour ETA" << endl;
for(int i = 2018; i <= (maxYears + 2018); ++i)
{
cout << i << endl;
for(int j = 10000; i <= (maxYears + 2018); j = j + (speedLight - j) *
(percentIncrease/100))
{
cout << "\t" << j << endl;
}
}
return 0;
}
I think a good way to think about it is that you will have to print the table row by row. So your first for loop seems to be doing that.
In each row, you have to, first, print the year (starting with the current year) up until the maximum year. Making the first for loop iterate over the years is a good choice (i.e. making i go from 2018 until maxYears + 2018). Second, you have to print the speed for each year after calculating the improvement via the provided equation. (I'm assuming that in the problem description it was given that the first speed is 10000? If not, what is the starting value?) Because you will only print a number, you don't need a second for loop. Just calculate the new speed and print it. As for the third and fourth column, I'm not sure what is asked exactly, so for now it will be blank in the code.
I modified code based on my comments, plus a few other modifications related to my understanding of the problem description, coding best practices, and stylistic choices (read below the code for more info on why).
#include <iostream>
//--1
int main()
{
//--2
const float speedLight = 299792;
const int startingYear = 2018;
//--3
float percentIncrease = 0;
while ((percentIncrease <= 0) || (percentIncrease >= 100))
{
std::cout << "What percentage do rocket speeds increase by each year?" << std::endl;
std::cin >> percentIncrease;
}
//--4
int maxYears = -1;
while (maxYears < 1)
{
std::cout << "What is the maximum number of years you are willing to wait on earth before you leave? " << std::endl;
std::cin >> maxYears;
}
std::cout << "Year|\tAvg Speed|\tEarth ETA|\tYour ETA" << std::endl;
//--5
float currentSpeed = 10000;
for (int year = startingYear; year <= (maxYears + startingYear); ++year)
{
//--6
std::cout << year << "\t" << currentSpeed << std::endl;
currentSpeed = currentSpeed + (speedLight - currentSpeed) * (percentIncrease / 100);
}
//--7
system("pause");
return 0;
}
--1: I removed unused libraries. (You may be using them for other parts
of the program, like if you want to print float numbers). I also
removed the using namespace std; because it is a bad practice. You
can google it.
--2: These numbers seem unchanging, so it is better to make them
constants.
--3: Maybe percentIncrease is not necessarily an integer.
--4: The problem description states that the number of years is a
positive integer, so it cannot be 0.
--5: The currentSpeed (previously j) should be defined outside the
loop because it will be updated inside the loop. Plus, it is a float
because of #3.
--6: The speed should be printed after the year.
--7: This is optional, in case you want the program window to not close
immediately. You can alternatively debug there by putting a
breakpoint, or any other solution.
Here's the important part of my code:
int realnum, positive = 0, total, poscount;
for (poscount = 1; poscount < 11; poscount++)
{
cin >> realnum;
while (realnum > 0)
{
total = realnum + positive;
}
}
cout << "Total of 10 positive values is " << total << endl;
I really just don't see what's wrong here. After declaring my integers the program goes into my for, increase the poscount to 2, asks my to input realnum. I put in a positive number (ex: 6), which should in theory add my realnum with positive (which I declared 0) and give total the value (ex: 6 + 0 = 6). It should keep looping until poscount reaches 11 and output the total of 10 positive numbers.
When I run it, I put in 6 and the command prompt just shows 6, nothing happens, and I have to close through the x button. Can someone please tell me what the error is?
I would just use a while in the outer loop, to keep the number of so-far positive numbers.
Also, your total is uninitialised and you assign positive to it, which is just 0?
This is what I have in mind:
int realnum, total = 0, poscount = 0;
while (poscount < 10) {
cin >> realnum;
if (realnum > 0)
{
total += realnum;
poscount++;
}
}
cout << "Total of 10 positive values is " << total << endl;
Replace your while with an if since currently, once you enter that while loop you never exit it.
Also, why are you always increasing poscount? Shouldn't you only do that if realnum is positive? The iteration statement in the for loop is allowed to be blank; then you write poscount++ inside the new if block.
You also need to write total += to increment the total amount.
These things are easy to spot if you use your debugger.
Okay, so I think I've corrected myself (without blatantly copying blurry but also using Bathsheba's tip on replacing my while.
int realnum = 1, positive = 0, total, poscount;
if (realnum > 0)
{
for (poscount = 1; poscount < 11; poscount++)
{
cin >> realnum;
total = realnum + positive;
positive = total;
}
}
cout << "Total of 10 positive values is " << total << endl;
So far, it seems to work, there's probably a lot of unnecessary things that make it inefficient but I didn't want to copy examples. *Edit of course I still need to do with the ignoring negative part
I think I backed myself into the point of no return, ha. I really thought there was an alternate way I was going... Anyways, thanks for your replies, guys. I've always been lurking around here, until I made an account now.
Add a condition to terminate the while loop. And instead of adding positive to realnum, try adding poscount. That should provide the desired result.
So, I hate to ask, but, I'm having some issue with this, I'm new to C++ and I'm just starting out. Everything is done for the most part. Expect for a little thing.
Line 35-36 should be calculating the average (Which for some reason, I haven't been able to get it to work.)
Line 41-47 should print out the percentage that heads/tails was landed on with precision to one decimal, and then print out the correct numbers of * to represent the percentage.
But, when I run it, my heads/tail count is messed up. As well as my percentage numbers. I'm just looking for a push in the right direction.
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <iomanip>
using std::cout; using std::cin; using std::endl;
using std::fixed; using std::setprecision;
int main()
{
srand(time(0));
int userInput,
toss,
headsCount,
tailsCount;
double headsPercent = 0,
tailsPercent = 0;
cout << "How many times do you want to toss the coin? ";
cin >> userInput;
while(userInput < 0)
{
cout << "Please enter a positive number: ";
cin >> userInput;
}
for(int i = 1; i < userInput; i++)
{
toss = rand() % 2;
if(toss == 0)
headsCount++;
else
tailsCount++;
}
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
cout << "Heads: " << headsCount << endl
<< "Tails: " << tailsCount << endl << endl;
cout << "Heads Percentage: " << fixed << setprecision(1) << headsPercent << " ";
for(int b = 0; b < headsPercent; b++)
cout << "*";
cout << "\nTails Percentage: " << tailsPercent << " ";
for(int b = 0; b < tailsPercent; b++)
cout << "*";
return 0;
}
In addition to the uninitialized variables here, that others have pointed out, the calculations are all wrong.
Take out paper and pencil, and run some your own calculations the old-fashioned way.
Let's say there were five tosses, three heads, two tails. This means that (after fixing the uninitialized variables):
userInput=5
headsCount=3
tailsCount=2
Now, here's how you're calculating your supposed percentages:
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
So, using your own numbers, you will get:
headsPercent = 5 / 3 * 100
tailsPercent = 5 / 2;
Does this look right to you? Of course not. You can do the arithmetic yourself. Divide 5 by 3 and multiply by 100. This is integer division, so five divided by three is 1, multiplied by 100 is 100. Five divided by two is two. So you get 100% and 2% here.
Of course, that's wrong. Two and three times, out of five, is 40% and 60%, respectively.
Writing a program means:
A) Figure out how calculations need to be made
B) Write the code to do the calculations.
You're still on step A. You need to figure out how you want to make these calculations so they're correct, first.
This has nothing really to do with C++. If you were using any other language, and coded this, in that manner, you'll get the same wrong answers.
The only thing this might have to do with C++ is that integer division, in C++ does not produce a fractional amount. It's integer division. But that's not your only problem.
Firstly u have to correct ur basics of mathematics.
Calculating %age means
example
(Marks obtained)/(Total marks)*100
Not (Total marks/marks obt)*100
Dividing any no by 0 is not defined. So if ur current code randomly assign toss or head =0, then obviously u will have errors.
Secondly talking about codes, U should either initialize i from 0 , or u should use
for (i=1; i<=userInput; i++)
As otherwise the head+toss value will be userInput-1.
Also remember to initialise variables like
Int headsCount=0;
etc. As the variable will take any random value if not initialised to a fixed no. (Though it does not creates a problem here)
And just change the datatype
int userInput,
toss,
headsCount,
tailsCount;
To
double userInput,
toss,
headsCount,
tailsCount;
This will solve your problem.
Advice: Please use
using namespace std;
in the starting of ur programs as u have to type a lot of std::
Welcome to C++. You need to initialise your variables. Your compiler should have warned you that you were using a variable without initialising it. When you don't initialise a value, your program has undefined behaviour.
I'm talking about headsCount and tailsCount. Something like this should be fine:
int headsCount = 0, tailsCount = 0;
Also note that your loop should start at 0, not 1, since you are using the < operator on the final condition.
Finally, your percentage calculations are backwards. It should be:
headsPercent = headsCount * 100 / userInput;
tailsPercent = tailsCount * 100 / userInput;
Now, there's a weird thing that might happen because you are using integer division. That is, your percentages might not add up to 100. What's happening here is integer truncation. Note that I dealt with some of this implicitly using the 100x scale first.
Or, since the percentages themselves are double, you can force the calculation to be double by casting one of the operands, thus avoiding integer truncation:
headsPercent = static_cast<double>(headsCount) / userInput * 100;
In fact, since the only two possibilities are heads and tails, you only need to count one of them. Then you can do:
tailsPercent = 100 - headsPercent;
1) This loop should start from 0:
for(int i = 1; i < userInput; i++)
2) The divisions are not correct:
//headsPercent = userInput / headsCount * 100;
//tailsPercent = userInput / tailsCount;
headsPercent = headsCount / userInput * 100;
tailsPercent = tailsCount / userInput * 100;
3) Finally:
cout << "\nTails Percentage: " << fixed << setprecision(1) << tailsPercent << " ";