This is my very first time posting of many, and I am in desperate need of help. I am attempting to put together a program to run Craps for school, and I am running into the error listed in the title. I have looked around here and messaged my professor, done everything he has asked, and yet still there is no fixing it. Rather than pester him again, could someone please help me figure out what to do next?
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
const int win1=7;
const int win2 =11;
const int crap1=2;
const int crap2=3;
const int crap3=12;
//prototypes for 5 functions are below, you need to code the bodies for these functions down below the main routine
int rollTheDice();
bool flag = false ;
bool winner( int );
bool craps( int );
void rollMore( int, double );
double getWager();
int diceRoll,dice1,dice2,roll,point;
double wager;
int main()
{
srand(34); //the final run will have 34, seed of 6 rolls a 7 -automatic winner, seed of 36 rolls 2-loser
cout << fixed << setprecision(2); //set output format
wager = getWager(); // call get wager and get back the amount the player wagered
cout<< "The amount wagered is "<<wager<<endl<<endl; //i added this cout to verify what wager is returned from getWager()
diceRoll = rollTheDice();
if( winner(diceRoll) ==true )
{
cout << "\nCongratulations! You have won " << wager << " $ \n";
}
else if( craps(diceRoll)==true) //call function craps and test if true is returned
{
cout << "\nSorry! You have lost " << wager << " $ \n";//print loser message and amount loss
}
else
{
rollMore( diceRoll, wager );
}
return 0;
//Get the user's wager amount with a cin and verify it before returning the value to main
double getWager()
{
cout << "Please enter your initial bet, in whole dollar amounts. The starting bet is 5.00$. \n" ;
cin >> wager ;
while (wager < 5)
{
cout << "I am sorry, the number you have entered is an insufficient bet. Please Try Again \n" ;
cin >> wager;
}
return wager;
}
int rollTheDice() //method is called and returns the roll of two dice, value between2-12
{ //you need two dice variables and generate a random number between 1-6 for each dice
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
diceRoll = dice1 + dice2;
roll=diceRoll;
cout << "You have rolled a " << diceRoll <<" \n";
return roll;
}
bool winner( int roll ) //returns true if roll is 7 or 11,else return false
{
if (roll==win1 or roll==win2)
{
return true;
}
else return false;
}
bool craps( int roll ) //returns true if player craps out which is a roll is 2,3,12,
if (roll==crap1 or roll==crap2 or roll==crap3)
return true ;
else return false ;
}
void rollMore( int point, int diceRoll, double wager, bool flag )
{
point=diceRoll;
cout << "You did not win or lose! We are now rolling to match the point by rolling " << point << "\n";
while (flag=false)
{
diceRoll = rollTheDice();
if (diceRoll==7)
cout << "\nSorry! You have lost " << wager << " $ \n";
flag == true ;
if (diceRoll=point)
cout << "\nCongratulations! You have won " << wager << " $ \n";
flag==true;
}
}
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
using namespace std;
int amount_total(int amount_paid, int& amountleft), quarters(int&
amountleft), dimes(int& amountleft), pennies(int& amountleft);
int amount_total(int amount_paid, int& amountleft)
{
const int TOTALVALUE = 99;
cout << "You have bought a candy bar that's 99 cents. \n"
<< "Please insert the amount paid. " << endl;
cin >> amount_paid;
amountleft = TOTALVALUE - amount_paid;
cout << "You have to pay : " << amountleft << " cents. \n" << endl;
return(0);
}
int quarters(int& amountleft)
{
const int QUARTERS = 25;
int total, count_Quarters;
count_Quarters = 0;
while (amountleft > 0 || amountleft >= QUARTERS)
{
total = amountleft - QUARTERS;
count_Quarters++;
}
return(count_Quarters);
}
int dimes(int& amountleft)
{
const int DIMES = 10, QUARTERS = 25;
int total, count_Dimes;
count_Dimes = 0;
while (amountleft > 0 || amountleft <= QUARTERS)
{
total = amountleft - DIMES;
count_Dimes++;
}
return(count_Dimes);
}
int pennies(int& amountleft)
{
const int PENNIES = 1, DIMES = 10;
int total, count_Pennies;
count_Pennies = 0;
while (amountleft >= 0 || amountleft <= DIMES)
{
total = amountleft - PENNIES;
count_Pennies++;
}
return(count_Pennies);
}
int main()
{
int amount_paid, amountleft, Count_Quarters,
Count_Dimes, Count_Pennies, total_amount;
total_amount = amount_total(amount_paid, amountleft);
Count_Quarters = quarters(amountleft);
Count_Dimes = dimes(amountleft);
Count_Pennies = pennies(amountleft);
cout << "You'll get : " << Count_Quarters << " quarters, " <<
Count_Dimes << " dimes, and " << Count_Pennies << " pennies. \n"
<< endl;
return 0;
}
//sample run:
You have bought a candy bar that's 99 cents.
Please insert the amount paid.
36
You have to pay : 63 cents.
What my original plan was for the program to run and the main would just run through the functions and the functions would return the variable, however it's not doing that and it's only running the first function
as rex mentioned in the comment all your while-loops are infinit and so will never stop looping. Your program actualling freezing inside your second function “quarters”. See how things happning there: when you left your function amount_total it returns 0 and assigns it to a “total_amount” variable, before it “amountleft” variable has been assigned the value equal to “TOTALVALUE – amount_paid”. You pass this value ( inside “amountleft” variable ) to the second function “quarters”. In case of your example “amountlef” variable is equal to 63 which is bigger than “0” and also bigger than QUARTERS ( as it is 25 ). So you are starting the loop here and each iteration of the loop your variable “amountleft” keeps having the same value i.e. 63 as it doesn’t change inside your while-loop, to leave the loop you have to change “amountleft” or to set any kind of break. To make it more visible it is possible to set “cout” inside your loops and see what is happeing there. Like this e.g.
21 int quarters( int& amountleft ) {
22 const int QUARTERS = 25;
23 int total, count_Quarters;
24 count_Quarters = 0;
25 cout << "before while-loop" << endl;
26 while( amountleft > 0 || amountleft >= QUARTERS ) {
27 cout << "count_Quarters = " << count_Quarters << endl;
28 cout << "amountleft = " << amountleft << endl;
29 total = amountleft - QUARTERS;
30
31 count_Quarters++;
32 }
33 cout << "after while-loop" << endl;
34 return count_Quarters;
35 }
Keep in mind that as you haven’t defined “total“ variable it can contain any garbage but usually don’t. Anyway it can be just good to assign any value ( such as 0 e.g. ) to a variable before using it.
I am facing difficulties in my C++ code. I am a beginner. Like, only with very basic knowledge of C++. So, I really can't figure a way to do this. I thought of making an RPG game using C++ commands and am close to finishing it. But somehow, I couldn't make a constant health for the hero. Taking a look at the code,
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class player
{ public:
int health = 100;
};
int battle();
void death();
int main()
{
int abc;
player hero;
hero.health = abc;
int a;
int replay = 1;
cout << "You have 100 Hp. \n";
while (replay == 1)
{
srand(time(0));
cout << "\n Press 1 to move forward; 2 To stay. \n";
cin >> a;
if (a == 2)
{
if (rand() % 4 + 1 != 1)
{
cout << "You stay at your place. \n";
}
else
{
cout << "Enemy Attacks! (20 Hp) \n";
//battle(hero.health);
//cout << "\n Press 1 to continue. \n";
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else if (a == 1)
{
if (rand() % 2 + 1 != 1)
{
cout << "You moved forward. No one around. \n";
}
else
{
cout << "You move forward. Enemy attacks! (20 Hp) \n";
battle(abc);
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else
{
cout << "Sorry. Please enter a valid move. \n";
}
}
return 0;
}
int battle(int x)
{
player enemy;
enemy.health = 20;
player hero;
int y;
while (enemy.health >= 0)
{
int eattack = rand() % 15 + 7;
int attack = rand() % 10 + 1;
int escape = rand() % 4 + 1;
cout << "\n Press 1 to attack. 2 to flee \n";
cin >> y;
if (y == 2)
{
if (escape != 1)
{
cout << "Can't escape! \n";
cout << "Enemy attacked! Dealing a damage of: " << eattack << " Hp. \n";
hero.health = hero.health - eattack;
cout << "Your Hp is: " << hero.health;
}
else
{
goto Aftermath;
}
}
else if (y != 1)
{
cout << "Sorry. Please enter a valid response. \n";
}
else
{
cout << "You attack the enemy. \n";
cout << "You deal a damage of: " << attack;
enemy.health = enemy.health - attack;
if (enemy.health >= 0)
{
cout << "\n Enemy attacks you, dealing: " << eattack << " Hp damage.";
hero.health = hero.health - eattack;
cout << "\n You have: " << hero.health << " Hp left.";
}
}
if ((hero.health <= 0) || (hero.health == 0))
{
death();
enemy.health = -1;
}
}
if (hero.health > 0)
{
cout << "\n Enemy fainted!";
//cout << "You found Hp Potion! Your Hp was refilled.";
}
Aftermath:
if ((hero.health > 0) && (enemy.health > 0))
{
cout << "Escaped Successfully! \n";
}
return x;
}
void death()
{
cout << "You died!";
}
As you see, I have called for battle(abc) and battle(hero.health) [which I have commented for now] but the problem is, it says "Too many arguments to function int battle(). Previously, I simply avoided parameters and created object "hero" in the battle method itself. But every time you get through a battle sequence, it comes back and declares it again, thus making its health refill. [Look at if (hero.health > 0) ]
I really don't know about global variables and all that. I just want to know if there is a workaround or a way to solve this parameter problem. Any other suggestions to have health as a 'constant' and not declared every time is also warmly accepted. Thank you so much!
P.S. Suggestions for shortening the code also accepted but please, I am a beginner. So advanced strategies are beyond my skills right now. I take time to grasp concepts.
You declare the function before the main method, and then you implement the function after the main method.
The problem is, you implement the function as:
int battle(int x)
but this doesn't match your declaration:
int battle();
Just change your function declaration block so the battle function matches the expected signature:
int battle(int x);
void death();
That will get your code compiling, but you are still a number of steps from getting this to work.
I'll give you one starter: instead of passing in the hitpoints into battle, pass the entire player.
void battle(Player &player)
{
// ...
}
Then you can modify the player's hitpoints directly in the battle function.
You would then call this with:
battle(hero);
I'm new to programming and I started to make my own Fire Emblem level up calculator, but for some reason it loops infinitely. I can't find an answer.
Could you look for any mistakes in my code, please?
#include<iostream>
#include<cstdlib>
#include<windows.h>
int main () {
using std::cout;
using std::cin;
using std::endl;
int level ,str , skl, lck, def, res, inc, hp, spd, nr ;
char cha[10];
nr=1;
cout<< "Which character?";
cin>> cha ;
cout<< "You chose" << cha << "." << endl << "What level do you want him/her to be?";
cin>> level ;
if (cha[6] = 'Dieck' ) {
hp = 26;
str = 9;
skl = 12;
spd = 10;
lck = 4;
def = 6;
res = 1;
while (level > 0) {
if (rand() % 100 < 90) {
inc=1;
//cout<< "HP increased by" << inc ;
hp+1;
}
if (rand() % 100 < 40) {
inc=1;
// cout<< "Strenght/Magic increased by" << inc ;
str+1;
}
if (rand() % 100 < 40) {
inc=1;
//cout<< "Skill increased by" << inc ;
skl+1;
}
if (rand() % 100 < 30) {
inc=1;
// cout<< "Speed increased by" << inc ;
spd+1;
}
if (rand() % 100 < 35) {
inc=1;
//cout<< "Luck increased by" << inc ;
lck+1;
}
if (rand() % 100 < 20) {
inc=1;
//cout<< "Defense increased by" << inc ;
def+1;
}
if (rand() % 100 < 15) {
inc=1;
//cout<< "Resistance increased by" << inc ;
res+1;
}
nr+1;
level-1;
//cout<<"NR."<< nr << " New stats (in order) HP/STR/SKL/SPD/LCK/DEF/RES " << hp <<" "<< str <<" "<< skl <<" "<< spd <<" "<< lck <<" "<< def <<" "<< res << endl;
Sleep(1);
}
cout<< "Stats "<< "HP/STR/SKL/SPD/LCK/DEF/RES " << hp <<" "<< str <<" "<< skl <<" "<< spd <<" "<< lck <<" "<< def <<" "<< res << endl;
return 0 ;
}
}
2011 version
std::strings, std::binds initializer lists, modern random number generators, auto variable typing. Shucks, even a few oldies-but-goodies like classes and error checking the input.
#include <iostream>
#include <random>
#include <functional>
#include <map>
// prep random number generator to simulate a 100 sided die
std::default_random_engine engine; // not being fancy here. Just using default RNG
std::uniform_int_distribution<int> uniform(1,100);// random from 1 to 100
auto d100 = std::bind ( uniform, engine ); // Convenience wrapper
void upstat(int & stat, // stat to increase
int chance, // odds of increase
int inc, // amount to increase
const std::string & statname)
{
if (d100() <= chance)
{ //less than or equal because I decided to emulate a d100.
// if the range was 0 - 99, only < would be necessary.
// such is the cost of slavishly adhering to dice conventions.
// std::cout<< statname << " increased by " << inc << std::endl;
stat += inc;
}
}
class Character
{
public:
Character(const std::string & name,
int level,
int HP,
int str,
int skl,
int spd,
int lck,
int def,
int res):
mName(name), mLevel(level), mStr(str), mSkl(skl), mLck(lck),
mDef(def), mRes(res), mHP(HP), mSpd(spd)
{
}
void levelup()
{
upstat(mHP, 90, 1, "HP");
upstat(mStr, 40, 1, "Strength/Magic");
upstat(mSkl, 40, 1, "Skill");
upstat(mSpd, 30, 1, "Speed");
upstat(mLck, 35, 1, "Luck");
upstat(mDef, 20, 1, "Defense");
upstat(mRes, 15, 1, "Resistance");
mLevel++;
}
// a couple useful getters
const std::string & getName()
{
return mName;
}
unsigned int getLevel()
{
return mLevel;
}
// out stream operator
friend std::ostream & operator<<(std::ostream & out,
const Character & ch)
{
out << "Stats " << "HP/STR/SKL/SPD/LCK/DEF/RES " <<
ch.mHP << " " <<
ch.mStr << " " <<
ch.mSkl << " " <<
ch.mSpd << " " <<
ch.mLck << " " <<
ch.mDef << " " <<
ch.mRes << std::endl;
return out;
}
private:
std::string mName;
unsigned int mLevel;
int mStr;
int mSkl;
int mLck;
int mDef;
int mRes;
int mHP;
int mSpd;
};
// name-indexed list of characters. Currently only contains Dieck.
std::map<std::string, Character> charlist{{"Dieck",{"Dieck",1, 26, 9, 12, 10, 4, 6, 1}}};
int main()
{
unsigned int finalLevel;
std::string cha; // using a string rather than a char array. Much less error prone.
std::cout << "Which character?" <<std::endl;
std::cin >> cha;
auto found = charlist.find(cha); // look in charlist for selected character
if (found != charlist.end()) // find returns end of list if not found
{
std::cout << "You chose " << found->second.getName() << "." << std::endl <<
found->second << std::endl; //optional. Print stats
for ( ; ; ) // Stay a while. Stay FOREVER! Muhuhahahahaha!
{
std::cout << "What level do you want him/her to be?" << std::endl;
if (std::cin >> finalLevel)
{
while (found->second.getLevel() < finalLevel)
{ // keep calling characer's level up routine until desired level reached
// or do nothing if the character is already a higher level.
found->second.levelup();
}
std::cout << found->second << std::endl; //optional. Print new stats
break; // breaks the infinite loop if input was good
}
else
{ // bad user input. Call user names until they get it right.
std::cout << "Valid positive numbers only, please." << std::endl;
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
}
}
}
else
{ // didn't find character. Do nothing.
// Should probably prompt to create new character here.
std::cout << "Character " << cha << " not found." << std::endl;
}
return 0;
}
2020 Rethink
Doesn't change much, but replaces std::bind with a Lambda expression.
std::default_random_engine engine;
std::uniform_int_distribution<int> uniform(1,100);
auto d100 = std::bind ( uniform, engine );
is replaced with
auto d100 = [](){
// all bundled up inside the lambda. No globals leaking out
static std::mt19937 gen{std::random_device{}()};
// explicitly specified the generator. Fewer surprises.
// this can be expensive, so it might be worth exposing gen and sharing it with
// other die-rolling lamdas
static std::uniform_int_distribution<int> uniform(1,100); // random from 1 to 100
return uniform(gen); // return result
};
level-1; computes the value of level-1 and then throws it away, doing essentially nothing. As such, the value in level is never updated and you're stuck with an infinite loop (you are also doing this with all of your variable updates, be careful!)
If you want to decrement the value of level (reduce it by one), you can do any of the following:
level = level - 1;
level -= 1;
level--;
Furthermore, if(cha[6] = 'Dieck') is not correct on several fronts. You could perhaps do
if(strcmp(cha, "Dieck") == 0) { //...
If you make sure to #include <cstring>
One issue you have is cha[6] = 'Dieck'
cha[6] is a single character such as 'D' or 'i' but not the whole thing. Also = sets cha[6] equal to 'Dieck' which can't happen because 'Dieck' is not a valid character. To compare them you'd need == but you can only compare one character at a time like cha[0] == 'D'
Really you should make your input a string, and use the compare() method of the string.
std::string input;
// stuff
cin >> input;
if (input.compare("Dieck") == 0)
{
// more stuff
}
You have two major problems which may cause compilation error.
nr+1;
level-1;
You have to assign them into some variable. Try this:
nr = nr+1;
or
nr++;
and
level = level -1;
or
level--;
now the while loop is not going to loop infinite.
Second problem is
if (cha[6] = 'Dieck' )
Note that, = is an assignment operator, not an equal operator. Equal operator looks like double equal ==. As you want to compare whether cha is equal to Dieck or not, try this:
if (strcmp (cha, "Dieck") == 0)
But you need to include #include<cstring> for that.
Reference here.
I'm having a problem assigning users to an array and then displaying the array. Typical 'flight seat-assign' program. Any help would be fantastic, as I am seriously stuck.
I haven't been getting any errors when compiling so I'm assuming I'm not too far off? code as follows.
Note, classes in separate header files.
// Flight Class - Scotia 2
// Contains information on seating (array), space available and return to menu option.
#include <iostream>
#include <string>
#include "booking.h"
using namespace std;
class Flight
{
public:
public:
struct Seat
{
int Available;
string fullName;
};// End of struct
// Structure for seat plan (24 spaces available)
struct Seat seatArray[4][6];
void seatPlan()
{ //------
cout << "Scotia Airlines Seating Plan\n";
cout << "------------------------\n";
cout << " 1D 2D 3D 4D 5D 6D\n";
cout << " 1C 2C 3C 4C 5C 6C\n";
cout << " \n";
cout << " 1B 2B 3B 4B 5B 6B\n";
cout << " 1A 2A 3A 4A 5A 6A\n";
cout << "------------------------\n\n\n";
//------
for (int i=0;i<4;i++)
{
for (int j=0;j<6;j++)
{
if (seatArray[i][j].Available == 0)
cout << seatArray[i][j].fullName << "=" << i+1;
else
cout << "Seating Plan is unavailable";
break;
}
}// End of for loop
}// End of seatPlan function
};// End of Flight class
Here is my booking class also, as I'm sure it'll help identify a problem...
//Booking class - Scotia Airlines
//This class will reserve a seat for passenger
#include <iostream>
#include <string>
using namespace std;
class Booking{
public:
struct Seat
{
int Available;
string fullName;
};// End of struct
// Structure for seat plan (24 spaces available)
struct Seat seatArray[4][6];
//variables for taking in customer details, calculating ticket cost (inc discounts) and adding details to system
public:
string fName, sName, busName, fullName;
int age, livesAt;
float discount, tickPrice, tCost;
void addBooking()
{
cout << "\tBooking Menu \n\n";
cout << "Please select ticket type: \n";
cout << "1- Business \n";
cout << "2- Western Isles \n";
cout << "3- Ordinary \n";
cin >> livesAt;
// This will be used to calc total cost for each passenger dependant on ticket type
if(livesAt == 1)
{
discount = 0.75;
cout << "Please enter your business name\n";
cin >> busName;
}
else if (livesAt == 2)
{
discount = 0.90;
}
else
{
discount = 1.0;
};
// Calculation - Standard ticket price is 60 Beans
tickPrice = 60.0;
tCost = (tickPrice * discount);
bool booked = false;
for(int i = 0; i < 4 && !booked; i++)
{
for(int j = 0; j < 6 && !booked; j++)
{
if(seatArray[i][j].Available == 1)
{
cout << "Please enter your first name \n";
cin >> fName;
cout << "Please enter your second name \n";
cin >> sName;
fullName == fName + " " + sName;
seatArray[i][j].fullName = fullName;
booked = true;
// Message on screen for customer displaying cost of flight
cout << "*******************************\n";
cout << "\tBooking for " << fName + " " + sName << " confirmed.\n";
cout << "\tTotal cost = " << tCost << " GBP.\n";
}//end of if
}//end of for2
}//end of for1
}// End of addBooking function
};// End of Booking class
Any help would be greatly appreciated!
Here are some errors I have spotted:
First of all you never mark a seat as not available. Add this to your add booing function.
Second the else in the second for in seatPlan should be in the else I believe.
You don't need a semi-column after an else statement(in the else when setting discount to 1.0)
As you never mention what are the errors you are getting this is as good as I can get. Hope this answer helps.