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
Related
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.
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 << " ";
Hi im looking for RandNum to generate a number between 2-10, and then that number being taken away from 15.
Right now, every time the program is executed, the number taken away from 15, (PerseusHealth) is 7. How do i fix this, and make it random?
void desertpath()
{
int scorpianchoice; //the option the player chooses.
int Maxhit = 10; //Max hit the scorpian can do
int Minhit = 2; //Min hit the scorpian can do
int randNum = rand()%(Maxhit + Minhit) + Minhit;
int healthremaining = PerseusHealth - randNum; //health left in option1.
if(scorpianchoice == 1)
{
cout << "You run under the Scorpians Legs in hopes to escape " << endl;
cout << "You are hit by the scorpians Sting for " << randNum << " hp!";
cout << "You have " << healthremaining << "/15 HP Left!" << endl;
cout << "You escape the Scorpian but not without taking some damage" << endl;
}
Use srand to initialize.
srand((unsigned)time(0));
Also, I think you have not put the brackets correctly:
int randNum = (rand()%(Maxhit - Minhit)) + Minhit;
Clarification on top of #ebad86 answer
rand() is known for bad quality, especially when low bits are used. Most likely, for example, output is always generated with low bit set to 1. Simple solution might be to use bits from the middle of the sequence by shifting bits (say, by 8)
If max generated output of rand() is not divisible by (Maxhit-Minhit), you'll get (slightly) biased result. It might be ok for your purposes, but you'd better know it