I'm currently writing a program where an user can input an amount that is dividable by the numbers 50, 20 and 10.
The way I'm trying to get it to work is that for example a user fills in the amount of 180, the program will calculate something like
"3 tickets of 50 have been used"
"1 ticket of 20 has been used"
"1 ticket of 10 has been used"
However, I have no idea where to even begin. I'm sorry if this is too vague but any help would be greatly appreciated
I tried to put my numbers into an array but that didn't work unfortunately. I also tried dividing them seperatly but that didn't work either
What I believe you want is a divide and reduce schema:
#include <iostream>
int main() {
std::cout << "enter amount: ";
if(long ui; std::cin >> ui) {
long c50s = ui / 50; // divide
ui -= c50s * 50; // reduce amount
long c20s = ui / 20; // divide
ui -= c20s * 20; // reduce amount
long c10s = ui / 10; // divide
ui -= c10s * 10; // reduce amount
std::cout
<< c50s << " tickets of 50 have been used\n"
<< c20s << " tickets of 20 have been used\n"
<< c10s << " tickets of 10 have been used\n"
<< "you have " << ui << " left\n"
;
} else {
std::cerr << "invalid input\n";
}
}
Example if giving 180 as input:
3 tickets of 50 have been used
1 tickets of 20 have been used
1 tickets of 10 have been used
you have 0 left
If you do this a lot, you could create a helper function:
long div_and_reduce(long& input, long div) {
long result = input / div; // divide
input -= result * div; // reduce
return result;
}
int main() {
std::cout << "enter amount: ";
if(long ui; std::cin >> ui) {
long c50s = div_and_reduce(ui, 50);
long c20s = div_and_reduce(ui, 20);
long c10s = div_and_reduce(ui, 10);
// ...
Any time you get stuck in programming, you should break the problem down. There are people who talk about "edit the null program until it does what it is suppose to." By this they mean start with nothing, and then address the first step (usually getting data into the program). Test it thoroughly. Then move onto the next step.
In your case, you need to collect data. So I would start with that. Start the program. Prompt the user and ask for the number they want. Just print it out. Make sure that works.
Then -- think about how you would do this manually. That will get you moving in the right direction for the next step. If that's too hard, then at least define the next step and break it down into pieces small enough you cna figure out how to do them, one step at a time.
Eventually the steps will be so small they are a line of code.
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;
}
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.
I'm working on a question which is asking me to have a guessing game with the computer... with the computer being the guesser:
"Write a program that calculates a random number 1 through 100. The program then asks the user to guess the number.
If the user guesses too high or too low then the program should output "too high" or "too low" accordingly.
The program must let the user continue to guess until the user correctly guesses the number.★ Modify the program to output how many guesses it took the user to correctly guess the right number.★★ Modify the program so that instead of the user guessing a number the computer came up with, the computer guesses the number that the user has secretely decided. The user must tell the computer whether it guesed too high or too low."
So far I've did the first couple bits, but I'm stuck on the two-star part, where the program guesses the number.
This is my code below: (but as you'll be able to tell, it doesn't quite work as planned)
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int compnumber;
string ok;
cout << "Think of a number between 1 and 100. Type 'ok' and I'll try and guess it." << endl;
cin >> ok;
cout << endl;
srand(time(NULL));
compnumber = rand() % 100 + 1;
cout << compnumber << endl;
cin >> ok;
while (ok != "correct")
{
if (ok == "high")
{
compnumber = rand() % compnumber + 1;
cout << compnumber << endl;
cin >> ok;
}
if (ok == "low")
{
compnumber = rand() % 100 + compnumber;
cout << compnumber << endl;
cin >> ok;
}
}
cout << "I won!" << endl;
}
I'm trying to figure out a way for the program to remember the number it previously guessed. I tried using the if (ok == "high") and if (ok == "low") to create what you'd call "boundaries" for the program "to remember". So if it was too high, it would remember the value it just guessed was too high, and would therefore guess lower than that, and vice versa with if it was too low.
But I'm struggling to get the program to remember both parts, e.g. if my secret number was 50, the computer guessed 80. I'd say it was too high, so it would go lower. If it then guessed 40, I'd say it was too low and it would go higher. But the program is then going HIGHER than it's original guess of 80, and sometimes even higher than 100 which I don't understand!
Any help would be appreciated. I have no idea if I'm going the right way with this, so any pointers would help! Thank you!
You need two extra variables - say int at_least = 1, at_most = 100; - as you get told "high" or "low", modify those to reflect the new knowledge of the range of possible answers. When you choose a new compnumber, keep it in that range by modding by the current size of the range and adding at_least.
You need two variables to store the high and low guesses so that the computer knows the range in which it should guess. Add this to your code:
int high = 101;
int low = 0;
Then when the computer guesses too high do this:
high = compnumber;
compnumber = ( rand() % (high-low - 1) ) + low;
And when too low, this:
low = compnumber;
compnumber = ( rand() % (high-low - 1) ) + low;
Hope that helps
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.