Stuck on a c++ lucky seven game program - c++

My Basic Algorithm:
Ask for input money amount; Rolls two 6-sided dice; if they add up to 7, add 4 to money amount; else, subtract 1 from money amount; loop until moneyamount<0; loop game user says n when prompted to play again.
/*
*File: hw3
*Author: Nathaniel Goodhue
*
*Created on: 9/15/15
*Description: Game of lucky sevens
*
*/
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
srand (time(NULL));
double moneyAmount;
int winValue = 7;
int numRolls = 0;
char playAgain = 'y';
while(playAgain == 'y')
{
cout<<"Enter the amount of money you are playing with: $";
cin>>moneyAmount;
while(moneyAmount>0)
{
int roll1= (rand()%6)+1;
int roll2 = (rand()%6)+1;
if(roll1+roll2 == winValue)
{
moneyAmount+=4;
numRolls++;
}
else
{
moneyAmount-=1;
numRolls++;
}
}
cout<<"It took "<<numRolls<<" roll(s) to lose all of your money"<<endl;
// cout<<"Your maximum amount of money was $" <<maxAmount<<" after "<<maxRolls<<" roll(s)"<<endl;
cout<<"Play again? y/n"<<endl;
cin>>playAgain;
if(playAgain == 'y')
{
cout<<"Enter the amount of money you are playing with: $";
cin>>moneyAmount;
numRolls = 0;
}
else
{
break;
}
}
return 0;
}
Above is my current code. It works as intended. What I am stuck on is that I need to be able to implement this line of code right after money drops below 0:
cout<<"Your maximum amount of money was $" <<maxAmount<<" after "<<maxRolls<<" roll(s)"<<endl;
I need to find out when there was the most money and after how many rolls that it appeared. The maxAmount variable would be the max amount of money achieved, and the maxRolls variable would be the number of rolls when maxAmount was reached.

This is pretty simple to add to your code. What you can do is check if the amount of money they have is greater than the max amount of money. If it is then set max to current and record the number of turns it took to get that value.
int maxAmount = moneyAmount, maxRolls = 0;
while(moneyAmount > 0)
{
int roll1 = (rand() % 6) + 1;
int roll2 = (rand() % 6) + 1;
numRolls++;
if(roll1 + roll2 == winValue)
moneyAmount += 4;
else
moneyAmount -= 1;
if (moneyAmount > maxAmount)
{
// the current amount of money is greater than the max so set max to current and get the number of rolls
maxAmount = moneyAmount;
maxRolls = numRolls;
}
}

Related

How to fix output not adding together?

Write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day and two pennies the second day, and continues to double each day. The program should ask the user for the number of days.
The output earnings should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
Basically, the output displays the correct answer mathematically it just does not add them together. I am not sure on what to do to fix that issue.
//Declare Variables
int numDays = 1;
double money = 0.01;
double totalPay;
//Initialize or input i.e. set variable values
cin>>numDays;
//Map inputs -> outputs
while (numDays < 1)
{
cout<<"Enter a positive value ONLY!\n";
cin>>numDays;
}
for (int i = 1; i <= numDays; i++)
{
cout<<"Pay = $"<<money;
money *=2;
}
//Exit stage right or left!
return 0;
Expected Output
Pay·=·$0.03
My Output
Pay·=·$0.01Pay·=·$0.02
//System Libraries
#include <iostream>//Input/Output Library
#include <iomanip>
using namespace std;
//User Libraries
//Global Constants, no Global Variables are allowed
//Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc...
//Function Prototypes
//Execution Begins Here!
int main(int argc, char** argv) {
//Set the random number seed
//Declare Variables
int numDays = 1;
double totalPay;
double dayPay;
double money = 1;
//Initialize or input i.e. set variable values
cin>>numDays;
//Map inputs -> outputs
while (numDays < 1)
{
cout<<"Enter a positive value ONLY!\n";
cin>>numDays;
}
for(int i = 1; i <= numDays; i++)
{
dayPay = money / 100;
totalPay += dayPay;
money *=2;
}
cout<<"Pay = $"<<fixed<<setprecision(2)<<totalPay;
//Exit stage right or left!
return 0;
}

Basic Value Swap function

I'm trying to design a piece of code that works like this. The user enters a 3 digit number, let's say they chose 653, they also input which numbers in that integer they wish to swap around. For example:
Enter a number and values you wish to swap: "653 2 3"
This then returns the following value:
635 is the new number.
I am trying to do this in a function I called digit_swap. Im not really sure how I to approach this as I'm very new to coding and even newer to coding. I think I have to seperate the integer into the units, tens and hundred components and to do that I did the following:
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
The only thing is, would I use a bunch of if statements to determine the swapping of the numbers or would it be a loop. I really have no idea how to go about this. As for my code I have the following.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else if (number >= 1000) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else {
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
}
}
using namespace std;
int main() {
int option_one, option_two;
int number;
cin >> number;
cin >> option_one >> option_two;
digit_swap(number, option_one, option_two);
cout << "New number = " << number;
}
Even when I test to see if it working by adding a return first in the else segment of the if statement it returns nothing. Any help is appreciated, I'm not asking you to do the code for me either.
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
// DO Something as you are doing
}
else {
third = (number % 10);
number /= 10;
second = (number % 10);
number /= 10;
first = (number % 10);
number /= 10;
}
if(InputOne == 1) {
if(InputTwo == 2) {
number += second*100 + first*10 + third;
}
else if(InputTwo == 3) {
number += third*100 + second*10 + first;
}
else{;}
}
else if(InputOne == 2) {
if(InputTwo == 3) {
number += first*100 + third*10 + second;
}
}
else{;}
return number;
}
I didn't test your code but I think there is an issue with the way you want to procede.
you want to modify "number" by passing it to your function
int digit_swap(int number, int InputOne, int InputTwo) {
int first, second, third;
if (number < 100) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else if (number >= 1000) {
cout << "Please enter a 3 digit integer\n";
exit(0);
}
else {
third = (number % 10);
second = ((number % 100)/10);
first = ((number % 1000)/100);
}
}
if you want to modify a variable inside a function and the change can be see outside you will need to use pointer. If you are new to programming I suggest you to do something like this in your main code. The way function works, it will create copy of all your parameter, the change you made on them are not on the originals one.
int main() {
int option_one, option_two;
int number;
cin >> number;
cin >> option_one >> option_two;
int result = digit_swap(number, option_one, option_two);
cout << "New number = " << result;
}
you store in the new result variable the "return of your function"
First you either need to pass number by reference otherwise number in digit_swap is just a copy of number in main(). Your other option is to just call the function like this:
number = digit_swap(number, option_one, option_two);
or by reference
void digit_swap(int & number, int InputOne, int InputTwo);
To help you with swaping i would suggest an int array.
int arr[3];
arr[0] = number / 100;
arr[1] = number / 10;
arr[2] = number % 10;
int temp = arr[InputOne-1];
arr[InputOne-1] = arr[InputTwo-1];
arr[InputTwo-1] = temp;
I hope that helps.

Basic C++ Dice game

I have a problem here, would be really nice if anyone could help me out here. Its my first time using this program so dont be to judgemental.
#include <cstdlib>
#include <iostream>
using namespace std;
int throw1, throw2, throw3, throw4;
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=(bet1, bet2, bet3);
int deposit;
int account;
int main(){
int count = 0;
while(count < 3){
cin>>deposit;
while(deposit>5000 || deposit<0){ //Makes sure so that my deposit is between 0-5000
cout<<"deposit failed"<<endl;
cin>>deposit;
}
account = deposit;
cout<<"You have deposited" <<deposit<<"Swedish Krona"<<endl;
cout<<"and you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
if (konto>499){ //Makes sure so that i have the money to bet, and if i dont have the money, i can just put in more
cout<<"please place your bet"<<endl;
cout<<"bet1=100, bet2=300, bet3=500"<<endl;
cin>>bet1;
cin>>bet2;
cin>>bet3;
account = (deposit - bet);
cout<<"you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
}
else if(account>299){
cout<<"please place your bet"<<endl;
cout<<"bet1=100, bet=300"<<endl;
cin>>bet1;
cin>>bet2;
account =(deposit - bet);
cout<<"you have this much cash on your account"<<account<<"Swedish Krona"<<endl;
}
else if(account>99){
cout<<"please place your bet"<<endl;
cout<<"bet1=100"<<endl;
cin>>bet1;
cout<<"you have placed your bet"<<bet<<"Swedish Krona"<<endl;
}
while (account<100 || deposit>5000){
cout<<"insufficient funds"<<endl;
cin>>deposit;
account=deposit;
}
{
cout<<"Throw dice"<<endl;
srand(time(0));
Throw1 = rand() % 6 + 1;
Throw2 = rand() % 6 + 1;
Throw3 = rand() % 6 + 1;
Throw4 = rand() % 6 + 1;
cout<<"You rolled"<<Throw1<<endl;
cout<<"You rolled"<<Throw2<<endl;
cout<<"Computer rolled"<<Throw3<<endl;
cout<<"Computer rolled"<<Throw4<<endl;
}
}
count++;
system ("pause");
}
So the thing here is that, for some reason i always bet 500, even though type in bet1 or bet2, and i have no clue how to fix that problem. And then my loop function (int count 0; while(count < 3)count++) it starts to loop endlessly without me pressing anything, even though i use the same loop function in simple coding like just typing some cout<< things it works fine, but when i use it in this code, it goes to drain, do anyone know why this is happening, would appreciate if anyone could answer, thanks in advanced.
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=(bet1, bet2, bet3)
The last line will be evaluated like this: 100, 300, 500. Result of comma separated list of expression will be last value, which is 500. So your bet variable will be always set to 500.
What you state in your comment below the code, (int count 0; while(count < 3)count++)looks like some weird mixture of for and while loop. Please check again your C++ textbook/online tutorials about how to write a correct loop.
In the code you show, in your while loop, you don't modify the count variable - therefore it will loop forever if count is < 3 before the loop. The indentation of your code is really misleading. I have taken the liberty of reformatting your code - and now you should see that the count++ statement actually is outside of your main while loop!
When you want to do something for a fixed number of times, it's recommendable to use a for loop, it makes it harder to forget the increment!
You increase count outside the loop, so it will always be zero. Either move it inside the loop (proper indentation is key!) or maybe use a for loop instead:
for (count = 0; count < 3; ++count) { ... }
Some advice,
place your prompt for deposit (insattning) into a function
place your prompt for bet into a function
check for sufficient money before prompting for bet
get input into a string, then validate input (not done below, yet)
check that bet is valid (=100,=300,=500, bet<=konto)
Here are these convenience functions,
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
int kast1, kast2, kast3, kast4;
int bet1 = 100;
int bet2 = 300;
int bet3 = 500;
int bet=0; //assignment didn't make sense
int insattning=0;
int konto=0;
//deposit
int get_insattning()
{
int good = 0;
while( !good )
{
cout<<"deposit"<<endl; //prompt for deposit
cin>>insattning;
if(insattning>5000 || insattning<0)//Makes sure so that my deposit is between 0-5000
{
cout<<"insattning fel, var vänlig och gör rätt denna gången"<<endl;
}
else good = 1;
}
cout<<"du har nu satt in" <<insattning<<"kr"<<endl;
return insattning;
}
It isn't clear to me whether you want 1 bet of 100,300,or 500, or 3 bets. This does the first,
//bet
int get_bet()
{
int good = 0;
int bet;
std::string validbets = "";
if(konto<100){ cout<<"you need more money"; return 0; }
while( !good )
{
cout<<"var vänlig och placera ditt bet"<<endl;
if(konto>=100){ validbets = "bet1=100"; }
if(konto>=300){ validbets += ", bet=300"; }
if(konto>=500){ validbets += ", bet=500"; }
cout<<validbets<<endl;
cin>>bet;
if( bet >= konto ) {
cout<<"you don't have enough money"<<endl;
continue;
}
if (bet==500){ //Makes sure so that i have the money to bet, and if i dont have the money, i can just put in more
cout<<"du har så här mycket på kontot nu "<<konto<<" kr"<<endl;
good = 1;
}
else if(bet==300){
cout<<"du har så mycket på kontot nu "<<konto<<" kr"<<endl;
good = 1;
}
else if(bet==100){
cout<<"du har nu bettat "<<bet<<" kr"<<endl;
good = 1;
}
else {
cout<<"you must place valid bet"<<endl;
continue;
}
}
return bet;
}
Now your main game play is cleaner/easier to read. I don't know what the win conditions are or the payout, and since your prompts are not english, I cannot read them to tell what to do next,
int main()
{
int count = 0;
int bet;
srand(time(0));
for( count=0; (count < 3); count++)
{
konto = get_insattning();
if (konto<100)
{
cout<<"du har inte nog med pengar, vänligen sätt in pengar"<<endl;
continue;
}
cout<<"och du har så här mycket i ditt konto "<<konto<<" kr"<<endl;
bet = get_bet();
//when you bet, reduce konto by bet
konto = (konto - bet);
{
cout<<"slå tärningar"<<endl;
kast1 = rand() % 6 + 1;
kast2 = rand() % 6 + 1;
kast3 = rand() % 6 + 1;
kast4 = rand() % 6 + 1;
cout<<"Du fick"<<kast1<<endl;
cout<<"du fick"<<kast2<<endl;
cout<<"datorn fick"<<kast3<<endl;
cout<<"datorn fick"<<kast4<<endl;
}
You need to write code for determining whether you won or lost, and then add to konto when you win,
//did you win or lose?
//win? add money to konto
//lose? you have already deducted from konto
}
system ("pause");
}
These suggestions should help you fix your program.

C++ floating point accuracy in while loops

I am trying to count the amount of dollar and coin denominations in a grand total by using a series of while loops. When I get down to the coins however, I am off by a penny. When I enter say 99.95, I get the output 3 quarters, 1 dime, 1 nickel, and 4 pennies. I've narrowed the problem down to a floating point accuracy issue. However all the solutions I've researched haven't been applicable in my situation. Any pointers?
#include <iostream>
using namespace std;
int main()
{
float amount;
cout<<"enter amount" << endl;
cin>>amount;
int pennies=0, nickels=0, dimes=0, quarters=0, ones=0, fives=0,
tens=0,
twenties=0, fifties=0, hundreds=0;
while (amount >= 100)
{
hundreds = hundreds +1;
amount = amount - 100;
}
while (amount >= 50)
{
fifties = fifties +1;
amount = amount - 50;
}
while (amount >= 20)
{
twenties = twenties +1;
amount = amount - 20;
}
while (amount >= 10)
{
tens = tens +1;
amount = amount - 10;
}
while (amount >= 5)
{
fives = fives +1;
amount = amount - 5;
}
while (amount >= 1)
{
ones = ones +1;
amount = amount - 1;
}
while (amount >= .25)
{
quarters = quarters +1;
amount = amount - .25;
}
while (amount >= .10)
{
dimes = dimes +1;
amount = amount - .10;
}
while (amount >= .05)
{
nickels = nickels +1;
amount = amount - .05;
}
while (amount >= .01)
{
pennies = pennies +1;
amount = amount - .01;
}
cout<<endl<<"pennies:"<< pennies;
cout<<endl<<"nickels:"<<nickels;
cout<<endl<<"dimes:"<<dimes;
cout<<endl<<"quarters:"<<quarters;
cout<<endl<<"ones:"<<ones;
cout<<endl<<"fives:"<<fives;
cout<<endl<<"tens:"<<tens;
cout<<endl<<"twenties:"<<twenties;
cout<<endl<<"fifties:"<<fifties;
cout<<endl<<"hundreds:"<<hundreds<<endl;
return 0;
}
Don't use floating point in cases where you need exact values. 99.95 can't be exactly represented in a float or double, a bit like 1/3 can't be exactly represented using a finite number of normal decimal digits.
As Doug T. suggested, you can use an integer to hold the number of pennies. When the user types 123.45, read it as two integers, and then store it as 12345 pennies, not as 123.45 dollars.
In this case, you can also try to change your last while (amount >= .01) to something like while (amount >= .005). It's not a solution that can be generally recommended, and if this is a real-life bank application you really should avoid it, but it will help against at least some of the errors.
You should be using fixed-point values in this case, not floating-point.
Although people think of money in terms of dollars, which aren't exact, money is measured in cents, which are exact. Just count the number of cents, divide by 100 to get the dollar amount, and take the modulus to get the cent amount. Floating-point is not the proper tool in this case.
Binary floating point numbers cannot, in general, represent fractional decimal values, even if the total number of decimals is small. For example, 0.1 cannot be represented exactly.
To deal with exact values different approaches exist which all amount to using a different base than 2. Depending on tge specific needs the approaches are more or less involved. The easieast approach for your case is to use a fixed precision instead of a variable precision. To compute with fixed precision you'd just use an integer which represents the value you actually want multiplied by a suitable power of 10. Depending on the amount of computations you do you can either package the logic into a class or distribute it throughout the code. In a "real" application I'd package it into a class, in an assignment (homework, interview, etc.) I'd probably just apply the logic directly to an int.
Here's the fixed code, I used TJD's advice and instead of using .01 i used .0099 instead. For my problem that seems to work, thanks guys!
#include <iostream>
using namespace std;
int main()
{
float amount;
cout<<"enter amount" << endl;
cin>>amount;
int pennies=0, nickels=0, dimes=0, quarters=0, ones=0, fives=0,
tens=0,
twenties=0, fifties=0, hundreds=0;
float p = .0099, n = .0499, d = .099, q = .2499;
while (amount >= 100)
{
hundreds = hundreds +1;
amount = amount - 100;
}
while (amount >= 50)
{
fifties = fifties +1;
amount = amount - 50;
}
while (amount >= 20)
{
twenties = twenties +1;
amount = amount - 20;
}
while (amount >= 10)
{
tens = tens +1;
amount = amount - 10;
}
while (amount >= 5)
{
fives = fives +1;
amount = amount - 5;
}
while (amount >= 1)
{
ones = ones +1;
amount = amount - 1;
}
while (amount >= q)
{
quarters = quarters +1;
amount = amount - q;
}
while (amount >= d)
{
dimes = dimes +1;
amount = amount - d;
}
while (amount >= n)
{
nickels = nickels +1;
amount = amount - n;
}
while (amount >= p)
{
pennies = pennies +1;
amount = amount - p;
}
cout<<endl<<"pennies:"<< pennies;
cout<<endl<<"nickels:"<<nickels;
cout<<endl<<"dimes:"<<dimes;
cout<<endl<<"quarters:"<<quarters;
cout<<endl<<"ones:"<<ones;
cout<<endl<<"fives:"<<fives;
cout<<endl<<"tens:"<<tens;
cout<<endl<<"twenties:"<<twenties;
cout<<endl<<"fifties:"<<fifties;
cout<<endl<<"hundreds:"<<hundreds<<endl;
return 0;
}

How do I generate a random number between two variables that I have stored? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating random integer from a range
I am trying to create a program where the computer guesses a number the user has in his/her mind. The only user input required is whether the guess was too high, too low, or correct. I'm having a problem generating a random number between two variables that store the min and max based on previous guesses. Here is my code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast <unsigned int> (time(0)));
int compGuess = rand() % 100 +1; //Generates number between 1 - 100
int highestNumber = 100;
int lowestNumber = 1;
char ready;
char highLowSuccess;
bool success;
int tries = 0;
cout << "Please pick a number between 1 - 100. I will guess your number. Don't tell me what it is!\n\n";
do
{
cout << "Are you ready? (y/n)\n\n";
cin >> ready;
if (ready == 'y')
{
do
{
cout << "Is your number " << compGuess << "?\n\n";
cout << "High, Low or Success?";
++tries;
cin >> highLowSuccess; //User input telling the computer whether its too high, too low, or a success
if (highLowSuccess == 'h') //Executes code if number guessed was too high.
{
highestNumber = compGuess - 1; //Stores variable indicating the highest possible number based on user input
compGuess = rand() % highestNumber +1; //Generates a new random number between 1 and the new highest possible number
success = false;
}
else if (highLowSuccess == 'l') //Executes code if number guessed was too low.
{
lowestNumber = compGuess + 1;//Stores variable indicating the lowest possible number based on user input
compGuess = (rand() % highestNumber - lowestNumber + 1) + lowestNumber // <---- Not producing the desired result
success = false;
}
else if (highLowSuccess == 's') //Executes code if the computer's guess was correct.
{
cout << "I guessed your number! It only took me " << tries << " tries!";
success = true;
}
} while (success != true);
}
else
{
continue;
}
} while (ready != 'y');
return 0;
}
highestNumber is what the max should be and lowestNumber is what the min should be. I need an equation that lets me generate a random number while taking the highest and lowest possible numbers into account.
Forgive me if the answer is really simple, I'm a noob programmer. xD
To generate a random number between min and max, use:
int randNum = rand()%(max-min + 1) + min;
(Includes max and min)
Really fast, really easy:
srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.
And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:
#include <random>
std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased
int r = gen(rng);
But you can also remove the bias in normal C++ like this:
int rangeRandomAlg2 (int min, int max){
int n = max - min + 1;
int remainder = RAND_MAX % n;
int x;
do{
x = rand();
}while (x >= RAND_MAX - remainder);
return min + x % n;
}
and that was gotten from this post.
If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:
//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);
That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...
Hope this helps
- Luke
rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber