I have to make a game of craps and towards the end, I have to do some probability. Here is my code so far. I want it so that the loop repeats 1000 times and looks for the 'probNumb' that the user entered. I am not sure if did this right but lets say I entered the number 5. This is what I get.
"Out of 1000 times, 5 was rolled 1000 times."
So, its not counting how many times 5 was rolled. I am not allowed to use break or continue statements, only loops and if else.
cout << "What number do you want the probability of ?";
cin >> probNumb;
while (probCount < 1000)
{
ranNumb= 1 + (rand() % (5 + 1));
ranNumb2= 1 + (rand() % (5 + 1));
ranNumbFin = ranNumb + ranNumb2;
probCount++;
if (ranNumbFin = probNumb)
probNumbCount++;
}
cout << "Out of 1000 times, " << probNumb << " was rolled "
<< probNumbCount << "times." << endl;
if (ranNumbFin = probNumb) is either a typo or should use ==
It's 1000 because the assignment returns the value assigned and since that's always non-zero in this case, it's always true.
it's a typo
if (ranNumbFin = probNumb)
should be
if (ranNumbFin == probNumb)
Your line if (ranNumbFin = probNumb) should be if (ranNumbFin == probNumb) - you're assigning, not comparing, which is causing the probNumbCount to increment every time.
My use of C and C++ is rusty, but I believe the ranNumb and ranNumb2 are not going to behave like dice rolls. These will just give a uniform random variate over 0 to 1.
Conceptually, for a six sided dice:
u = rand();
if(u < 1/6) ranNumb=1;
elseif(u < 2/6) ranNumb=2;
elseif(u < 3/5) ranNumb = 3;
An so on. There is probably a better performing method.
Related
I am writing this program which will guess the number user is thinking about. After days of work, I could not figure out what is wrong in it.
Also my proposed grade for the assignment is not what I expected.
Please help.
User can guess 100, but my program uses mid-point rule so can only go up to 99. How can I make 100 inclusive?
If I keep pressing 'l' the program will eventually break out of loop and prints If you want to try again?
Is there a better way to code this program? Example please.
Here is the actual program:
Write a program in that can figure out a number chosen by a human user. The human user will think of a number between 1 and 100. The program will make guesses and the user will tell the program to guess higher or lower. The program should find the midpoint of the two numbers and ask if the number is higher or lower.
#include <iostream>
using namespace std;
int main() {
char check;
char tryagain;
do {
int midpoint;
const int MAX = 100;
const int MIN = 1;
int y = MAX;
int x = MIN;
cout << "Think of a number between 1 and 100." << endl;
midpoint = (x + y) / 2;
while (x != y || y != x) {
cout << endl << "Is it" << " " << midpoint << " " << "?";
cin >> check;
if (check == 'l' || check == 'L') {
y = midpoint;
midpoint = (x + y) / 2;
}
else if (check == 'h' || check == 'H') {
x = midpoint;
midpoint = (x + y) / 2;
}
else if (check == 'c' || check == 'C') {
break;
}
else {
cout << "Incorrect choice." << endl;
}
}
cout << "Great! Do you want to try again? (y/n)";
cout << endl;
cin >> tryagain;
} while (tryagain == 'y' || tryagain != 'n');
return 0;
}
Your problem is just a mis-think in the calculation of x and y like Alf suggested in the comments.
It should read
y = midpoint - 1;
and
x = midpoint + 1;
respectively. The reason is simple. You use midpoint as the guess. The guess is then no longer part of the available guesses. Your first guess is 50, x or y should then be either 51 or 49 as the new min or max in the interval.
This will also make 100 included in the available guesses. The last step in the calculation will be when midpoint was 99 and the user selects 'h'.
x = 99 + 1;
lower bound is 100, and the midpoint guess evaluates to
midpoint = (100 + 100) / 2;
which is correct.
As for better ways to write this program. This would depend on what your course has taught you, what's in the curriculum, and so on. You might want to check out code-review
When your x and y are too close, the division of their sum produces an incorrect midpoint. 100 + 99 / 2 = 99 (which is 99.5 rounded down). You need to check for this special case. At the end of the loop before the closing bracket insert:
if ( y-x < 2) midpoint = y;
User can guess 100, but my program uses mid-point rule so can only go up to 99. How can I make 100 inclusive?
Division of integers in c++ discards any decimal. It always rounds down. Consider what happens when midpoint is 99. You get midpoint = (99 + 100) / 2 which is 199 / 2 which is 99.5. Discarding the decimal leaves you with 99 every time. One possible solution is to change y = midpoint; to y = midpoint - 1; and x = midpoint; to x = midpoint + 1; This will prevent your application from guessing the same value more than once. With this change, when midpoint is 99, x will first be incremented to 100 giving us a new midpoint (100 + 100) / 2 which evaluates to 100.
If I keep pressing 'l' the program will eventually break out of loop and prints If you want to try again?
If the user keeps pressing l then eventually the only possible solution is 1. It seems that you chose not to propose your guess at that point and assume the user followed the rules. Add an extra print when the answer is deduced.
if (x == y) {
// Answer was deduced
cout << "You guessed " << x << ".\n";
}
Is there a better way to code this program? Example please.
See the first two parts of this answer. Other than that, it's difficult to say objectively what "better way to code this" means. You might want to consider a system to detect when the user is lying. For example, if midpoint == x then the user can't select l without lying.
I'm trying a lab exercise which wants user to input a 2 4-digit integer. Then the program will extract all the numbers in the 4-digit integer and use the number to do an arithmetic calculation just like the image link below.
Arithmetic Calculation with 2 4-digit integer
However, the objective for this lab exercise is not to allow me myself, to use a for loop to obtain the result.
For instance, when i want to obtain the last number of the 4 digit integer, I could easily do it by using this.
int firstDigit = firstNo % 10; //i will get 4 if the integer is 1234
int secondDigit = secondNo % 10; //i will get 8 if the integer is 5678
And of course table formatting is nothing to worry about before getting the logic right. Next is a very simple calculation of the numbers using the digit i obtain from the above.
int addfirstNumbers = firstDigit + secondDigit;
int minusfirstNumbers = firstDigit - secondDigit;
int multiplefirstNumbers = firstDigit * secondDigit;
int modfirstNumbers = firstDigit % secondDigit;
double divfirstNumbers = firstDigit / secondDigit;
cout << "add: " << addfirstNumbers << endl
<< "minus " << minusfirstNumbers << endl
<< "multipile " << multiplefirstNumbers << endl
<< "remainder " << modfirstNumbers << endl
<< "division " << divfirstNumbers << endl;
I do understand forloop can make my life easier. But i'm just trying out the long method before trying out the shorter way which is forloop.
But even before i proceed, I'm still unable to extract out the other digit from this 4 digit integer.
Like Mike Vine mentioned in the comments, you can do integer division before taking the modulo.
#include <iostream>
int main(){
int x = 1234;
std::cout << (x/10)%10 << "\n";
}
#Output
3
Edit: This works for all places of a number. To find the nth value from the end, just keep adding 0s to the divisor. For example to find the 2nd from the last, you'd want to divide x by 100 instead.
You could simply do
int secondLastDigit = ((i - (i % 10)) % 100)) / 10;
For i=5678:
i % 10 (5678 % 10) equals 8
i - (i % 10) (5678 - 8) therefore equals 5670.
(i - (i % 10)) % 100 (5670 % 100) equals 70
Finally (i - (i % 10)) % 100) / 10 (70 / 10) = 7
This is pretty simple, just use the modulus operator on the number for 100(num%100), getting the last two digits that way, and then divide that result by ten, and store the digit in an int (so the decimal is properly truncated.)
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 << " ";
It just keeps looping. The numbers continue decreasing until the program is closed. Am I misusing something?
The playerHealth and orcHealth ints are 100.
randomNumber = ("%10d", 1 + (rand() % 100));
This was the way I seen the random number used on an srand() explanation page. If this is wrong, how should it be?
Are there any other problems here?
switch(charDecision)
{
case 1:
cout << "FIGHT" << endl;
do{
randomNumber = ("%10d", 1 + (rand() % 100));
if(randomNumber >= 50){
orcHealth = orcHealth - (randomNumber - (randomNumber / 5));
cout << "You hit the orc! He now has " << orcHealth << " life left!" << endl;
}
else
{
playerHealth = playerHealth - (randomNumber - (randomNumber / 5));
cout << "The orc hit you! You now have " << playerHealth << " life left!" << endl;
}
}while(playerHealth || orcHealth >= 0);
break;
default:
break;
}
playerHealth || orcHealth >= 0 does not mean "while playerhealth greater than zero OR orchealth greater than zero". It means "while playerhealth, cast to boolean is true OR orchealth greater than zero".
This
}while(playerHealth || orcHealth >= 0);
should probably be
}while(playerHealth > 0 && orcHealth > 0);
I think you want to exit the loop, if either one is 0 or less.
Also, change randomNumber = ("%10d", 1 + (rand() % 100)); to randomNumber = 1 + rand() % 100;
The comma operator just obfuscates the code.
Your condition for the do...while statement will stop at some point, but only at some point. This means, your condition will be met if either playerHealth is zero or orcHealth is smaller than zero. What if the playerHealth gets below zero? This is very likely since you are always deducting a number from both character's healths. A possibility of playerHealth becoming exactly zero is a very tiny one. And when the playerHealth goes below zero, its possibility of becoming zero is still very unlikely, even due to integer overflow. So, if you want to "kill" the character when one of their health becomes zero or less, you better change that line with something like
while ( playerHealth > 0 && orcHealth > 0 )
On a side note, the || statement works if any one of the statements is true. In C++, for an integer a 0 value is false, all other values -including negative ones- are treated as true. Also, the || checks from left to right and when it finds the first true statement, it stops searching. In your case, it checks playerHealth, which is very likely nonzero. When it sees this expression is true, it decides that the whole statement inside the parantheses is true and skips checking orcHealth >= 0. This results in the infinite loop. You might want to look at the order of evaluation of conditionals in C++, maybe something like this post.