Generating numbers outside of my range C++ (way too large) - c++

I decided for fun to try and make a simple program that "sort of" simulates blackjack in a dumbed down way. It's basically done, except for the fact that the randomly generated numbers are WAY too large. I don't care about the bias srand/rand has (for now) I just want to get it working properly.
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
int genRandInt (int low, int high) {
int randnum = low + (rand() % (high - low + 1));
return randnum;
}
int main()
{
srand(time(NULL));
int computerScore;
int score;
int card;
while (int playAgain = 1)
{
cout << "Enter 0 to hold or 1 to hit: ";
int play;
cin >> play;
if (play == 0)
{
computerScore = genRandInt(1, 31);
if (score < computerScore)
{
cout << "Your score is " << score << " and the computer's score is " << computerScore << "! You lose.\n";
}
if (score > 21)
{
cout << "Your score is " << score << " which is greater than 21. Bust!\n";
}
if (score > computerScore && score <= 21)
{
cout << "Your score is " << score << " and the computer's score is " << computerScore << "! You win!\n";
}
cout << "Would you like to play again? 1 for yes, 0 for no. : ";
cin >> playAgain;
}
if (play == 1)
{
card = genRandInt(1, 11);
score = score + card;
cout << "Your score is: " << score << "\n";
}
}
return 0;
}
Any ideas?

You use int score; uninitialized in
if (score < computerScore)
or
score = score + card;
depending on the if(play == 0) or if(play == 1) condition.
It happens to have some junk as its memory content, the compiler does not initializes to zero for you. In fact, it is undefined behaviour to use un-initialized variables. Initialize it before the first usage, preferable in the definition itself,
int score = 0;
Also, compile with warnings on (-Wall -Wextra for g++/clang++), since the compiler will easily warn about these mistakes.

Try running this and seeing if you have the same issues. I just added some print statements to try and debug it, and it stopped showing me really big numbers..
EDIT:
//ADD
int score = 0;
//
if (play == 1)
{
cout << "printing in the PLAY = 1 "<< score << endl;
card = genRandInt(1, 11);
score = score + card;
cout << "Your score is: " << score << "\n";
}

Related

How to code in C++ mutiple return values to main from mutiple modules and display each modules totals?

I must write a program where the user can choose to practice with topic addition or topic multiplication that starts with a self-driven menu.
It must keep track of questions answered right, wrong and the number of questioned asked.
Which my current program is doing within each module(topic). Example Addition keeps track of the questions while the user is practicing Addition only and Multiplication does the same.
However, they are not being feedback to main, so they are not being added or displayed before the user can select another topic to practice or to exit the program.
Currently it is only to keeping track of the question (right /wrong/ total of questions) for each module (topic).
My goal is for the values to be passed to main and display the total number (right /wrong/ total of questions) before the user exits the program, but at the same time I must display the number of question in the Additional Topic and the Multiplication topic and provide a total.
Example Table of Addition, Multiplication and Totals ?
This is the code I have to start with. Can someone help me in how to code to return values of the (right /wrong/ total of questions) of the two topics and accomplish to display something like the table information.
******************************************************************************* /
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string> // String managment funtions.
#include <iostream> // For input and output
#include <cmath> // For math functions.
#include <math.h>
#include <cstdlib>
using namespace std;
////////////////////////////////////////////////////////////////////////
// Implementing menu driven programs.
// Function Prototypes.
int menu();
void sums();
void products();
int main()
{
srand(time(0));
int option;
do {
option = menu();
switch (option) {
case 1: {
sums();
break;
}
case 2: {
products();
break;
}
default:
cout << "Program exit" << endl;
}
} while (option != 6);
return 0;
}
int menu()
{
cout << "Please select an option" << endl;
cout << "1) Practice with Addition " << endl;
cout << "2) Pratice with Multiplication " << endl;
cout << "3) Exit the program " << endl;
int option;
cin >> option;
return option;
}
void sums()
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValue = 10;
const int maxValue = 99;
int y = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is x "<< x << endl;
cout << "What is " << x << " + " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x + y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
void products()
{
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValueOne = 0;
const int maxValueOne = 9;
const int minValueTwo = 10;
const int maxValueTwo = 99;
int y = (rand() % (maxValueOne - minValueOne + 1)) + minValueOne;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValueTwo - minValueTwo + 1)) + minValueTwo;
// cout<< " the random number is x "<< x << endl;
cout << " What is " << x << " x " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x * y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
}
I would create a structure that contains the number of total answers and number of correct answers—the incorrect ones can be inferred—and then pass a reference to an instance of the structure to the respective sums() and products() functions.
Those functions can then populate the structure elements and when they return, your main function can read them out, knowing exactly how many questions were asked, how many were answered, or whatever other information you want to record and retrieve.

For loop - Magic number program

What changes should I make so that the user of this code can guess at the amount of magic numbers they choose, with three different chances to guess at each magic number? I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
int magic; // This is a random number between 1 and 20
int guess; // This is the guess number being attempted (up to 3 guesses)
int magicguesses; // This is the amount of magic numbers being guessed attempted
int i;
int number; // This is the number the user guessed
bool numberismagic = false; // This is the flag variable
unsigned int seed;
seed = time(NULL);
srand(seed);
magic = rand() % 20 + 1;
cout << "How many magic numbers would you like to guess at today?\n";
cin >> magicguesses;
for (i = 1; i < magicguesses + 1; i++)
{
cout << "This is trial number:" << i << endl;
for (guess = 1; (guess < 4) && (!numberismagic); guess++)
{
cout << "This is guess number:" << guess << endl;
cout << "Guess a number between 1 and 20:" << endl;
cin >> number;
while ((number < 1) || (number > 20))
{
cout << "Your guess is invalid; guess a number between 1 and 20 \n";
cin >> number;
cout << endl;
}
if (number == magic)
{
cout << "You have guessed the magic number correctly! \n";
numberismagic = true;
}
else
{
cout << "Sorry - you guessed incorrectly! \n";
if (number > magic)
cout << "Your guess is too high \n" << endl;
else
cout << "Your guess is too low \n" << endl;
}
}
if (number != magic)
cout << "The magic number is:" << magic << endl;
}
return 0;
}
I'm not sure what your first question is, but for this question "I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly", you should edit the variable magic inside the first for loop so the magic number changes after the user guesses correctly or they run out of tries.
for (i=1;i<magicguesses+1;i++)
{
//magic equals new random number
//the rest of your code
}

Printing a scoreboard with a sliding arrow C++ beginner

I am working on a program to code a game called Devil's Dice. I have the logic of code working perfectly, but I am struggling to print the scoreboard to show the games progress. The details of the assignment are below, followed by my code. I don't know where to begin printing the scoreboard as shown in the image I linked.
In our version of Devil's Dice the rules will be as follows:
The player repeatedly rolls a 6-sided die until either a 1 is rolled or the player decides to "hold".
If the player rolls a 1, they lose any points accumulated this turn and the devil gets a turn.
If the player rolls any other number, it is added to their turn total and the player's turn continues.
If a player chooses to "hold", their current turn total is added to their score and the devil gets a turn.
Devil's Logic
If the score is tied or the devil is winning, he will keep rolling until he has at least 21 points (unless he has already reached 100 points)
If the player is winning, the devil will keep rolling until he has at least 30 points (unless he has already reached 100 points)
If the devil rolls a 1, he also loses the points he has accumulated on his turn
If the player chooses to "forfeit", they lose and the game is over.
The player must score 100 points before the devil manages to do so in order to win.
For example, the player, Ann, begins a turn with a roll of 5. Ann could hold and score 5 points, but chooses to roll again. Ann rolls a 2, and could hold with a turn total of 7 points, but chooses to roll again. Ann rolls a 1, and must end her turn without scoring. The devil then rolls the sequence 4-5-3-5-5, chooses to hold, and adds his turn total of 22 points to his score.
There are a few other details about the game logic but i am confident i have it working correctly. I am just wondering how to get a menu with a moving arrow as shown below.
My code looks like this:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() { //just for a school grading program//
#ifdef JARVIS
srand(0);
#else
srand(time(NULL));
#endif
// Call your functions to play your game here...
char userInput;
int diceRoll;
int turnScore = 0;
int totalScore = 0;
int devilScore = 0;
bool isItDevilsTurn = false;
bool winner = false;
int devilWins = 0;
int playerWins = 0;
cout << "---- Welcome to Devil's Dice! ----" << endl;
cout << "Hold[h], roll[r], or forfeit[f]: " << endl;
while (!winner) {
if (!isItDevilsTurn) {
cin >> userInput;
if (userInput == 'h')
{
totalScore = totalScore + turnScore;
cout << "You banked " << turnScore << " points and have a total of " << totalScore << " points" << endl;
isItDevilsTurn = true;
turnScore = 0;
}
if (userInput == 'r')
{
diceRoll = rand() % 6 + 1;
if (diceRoll > 1)
{
cout << "You rolled a " << diceRoll << "!" << endl;
turnScore = turnScore + diceRoll;
}
else
{
cout << "You rolled a 1 :(" << endl;
turnScore = 0;
isItDevilsTurn = true;
}
}
if (totalScore >= 100) {
winner = true;
cout << "You Win!" << endl;
playerWins = playerWins + 1;
}
if (userInput == 'f') {
cout << "Game Over!" << endl;
}
}
else
{
int devilGoal = 21;
if (totalScore > devilScore)
{
devilGoal = 30;
}
while (isItDevilsTurn)
{
diceRoll = rand() % 6 + 1;
if (diceRoll > 1 && turnScore < devilGoal)
{
cout << "devil rolled " << diceRoll << endl;
turnScore = turnScore + diceRoll;
}
else if (diceRoll > 1 && turnScore > devilGoal)
{
devilScore = devilScore + turnScore;
cout << "devil holds " << turnScore << " points and now has " << devilScore << " points" << endl;
isItDevilsTurn = false;
turnScore = 0;
}
else
{
cout << "devil rolled a 1" << endl;
isItDevilsTurn = false;
turnScore = 0;
}
if (devilScore >= 100)
{
cout << "Devil Wins!" << endl;
devilWins = devilWins + 1;
winner = true;
}
}
}
}
cout << "Total Wins: " << playerWins << endl;
cout << "Total Losses: " << devilWins << endl;
fstream output("games.txt");
output << playerWins << " " << devilWins << endl;
return 0;
}
I'm sorry, I'm not too good with tabs, so you just make it looks like you need to. I used a ternary operator to understand if I need to write number or a tab in cuurent line
printf("\tPlayer\t\t\tDevil\n");
printf("\t------\t\t\t-----\n");
for(int i = 10; i >= 0; --i){
printf((totalScore < (i+1)*10 && totalScore >=i*10) ? "%d >" : "\t", totalScore);
printf("--%d", i*10);
printf((turnScore < (i+1)*10 && turnScore >=i*10) ? "< %d" : "\t\t\t", turnScore);
printf((devilTotal < (i+1)*10 && devilTotal >=i*10) ? "%d >" : "\t", devilTotal);
printf("--%d", i*10);
printf((devilTurn < (i+1)*10 && devilTurn >=i*10) ? "< %d" : "\t\t", devilTurn);
printf("\n");
}
How it works? first printf() I evaluate totalScore, if it's less then next value and more than current I print it, otherwise just print tab. Second printf() prints current value. Third printf() evalutes turnScore, if it's less then next value and more than current I print it, otherwise just print 2 tabs.
Same for devil.
It would be the same with cin and cout, it's just that I feel more confident with printf(). If it looks right, all you need to do is work with alignments.

Can't get function to work right. Extra numbers that shouldn't be displayed

I am new to C++ and programming in general so this is all difficult for me but I am really trying to learn. I can't get the letterGrade function to display correctly. I gives me the letter grade like it should but also adds a bunch of numbers after the letter grade. Could anyone please let me know what is going on and what I am doing wrong? Also I am supposed to use a function to find the average but I can only make it work by defining a variable sAverage in my "for" loop to display the array like a table. I had created a function for that as well but it didn't give me the right answer. Here is my code.
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int letterGrade(int average)
{
if (average > 89)
cout << "A";
else if (average > 79 && average < 90)
cout << "B";
else if (average > 69 && average < 80)
cout << "C";
else if (average > 59 && average < 70)
cout << "D";
else if (average >= 0 && average < 60)
cout << "F";
}
void getInfo()
{
const int info = 2;
string last[info];
string first[info];
int ID[info];
int score1[info];
int score2[info];
int score3[info];
for (int count = 0; count < info; count++)
{
cout << "last name\n";
cin >> last[count];
cout << "first name\n";
cin >> first[count];
cout << "enter ID\n";
cin >> ID[count];
cout << "enter test 1\n";
cin >> score1[count];
cout << "enter test 2\n";
cin >> score2[count];
cout << "enter test 3\n";
cin >> score3[count];
}
cout << endl;
cout << "Last Name\tFirst Name\tID\tTest 1\tTest 2\tTest 3\tAverage\t Grade\n";
cout << "__________________________________________________________________\n";
for (int count = 0; count < info; count++)
{
int sAverage = ((score1[count]+score2[count]+score3[count])/3);
cout << setw(10) << last[count]
<< setw(10) << first[count]
<< setw(10) << ID[count]
<< setw(10) << score1[count]
<< setw(10) << score2[count]
<< setw(10) << score3[count]
<< setw(10) << sAverage
<< setw(10) << letterGrade(sAverage);
cout << endl;
}
}
int main(int argc, char *argv[])
{
cout << "Enter Student Info\n";
getInfo();
system("PAUSE");
return EXIT_SUCCESS;
}
The function I had to find the average was:
int getAverage(score1, score2, score3)
{
int average;
average = ((score1 + score2 + score3) / 3);
return average;
}
I called it like this
cout << getAverage(score1[info],score2[info],score3[info])
but it only came back with a high number in the hundreds but what I need is a function do average the scores in the array from the input.
Thanks in advance and again I am new to all this.
When you call the function:
cout << getAverage(score1[info],score2[info],score3[info])
where info is equal to 2, you're accessing memory out of bounds of the array. You're length of an array is 2, so the only valid indices are 0,1 - not 2.
Moreover, in the definition of function:
int getAverage(score1, score2, score3)
{
int average;
average = ((score1 + score2 + score3) / 3);
return average;
}
You didn't specify the types of scoreX variables, and the the implicit int rule is not valid in C++.
EDIT:
Another thing: when you're calculating the average, you have to remember that dividing an integer by an integer always gives an integer, so if you want to have more precise answer, e.g. for 2.66 2 3 3, you have to use a float.
Maybe you mis-read your output? The getAverage function should work correctly even though you didn't specify types for the parameters (they default to int, then).
It looks like your problem is a different one: your function letterGrade doesn't have a return statement, so it returns random junk. Your compiler should actually warn you about that. This junk is interpreted as a number (since you said the function is returning int) and formatted that way.
What you probably want is something like:
string letterGrade(int average)
{
if (average > 89)
return "A";
else if (average > 79 && average < 90)
return "B";
else if (average > 69 && average < 80)
return "C";
else if (average > 59 && average < 70)
return "D";
else if (average >= 0 && average < 60)
return "F";
else
return "-"; // negative value was passed!
}
You use << within a function without flushing cout. In fact, you say in the letterGrade prototype that you return an int but you don't, so when you call something like cout << letterGrade(...), it prints a random number
The protoype of letterGrade should rather be :
string letterGrade(int average)
and you must return your letter (using for example return "F"; instead of cout << "F").
It is often bad idea to print on the standard output without endl nor cout.fflush().

How to keep track of a score -- C++ Console

I am making a poker game in C++ for a my intro to C++ class (should tell you that I am only a beginner so please excuse any bad programmer practice here). I am currently working on the betting system, in which I am quite pleased it does what I need it to do. Except that it doesn't carry on - the game just resets after the hand. Here's my code, I was thinking I need to make separate classes and then call those classes in the main, but I'm just not sure how that would be any different, if that's the case then I'll delete this question.
{// ConsoleApplication71.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include "Bet.h"
using namespace std;
//Bet P = int betP(int money);
int main()
{
bool win;
bool lose;
int Omoney = 100;
int money = 0;
int Tmoney = 0;
int bet = 0;
int earn = (bet * 2) + Omoney;
int loseM = 0;
loseM = loseM + bet;
cout << "Your start money = " << Omoney << " \n\n\n" << endl;
cout << "Place your bet here!" << endl;
cin >> bet;
money = Omoney - bet;
cout << "Your total money after bet is " << money << "\n\n";
//betP(int money)
//{
// money - bet = money;
//}
if (bet > 10)
{
win = true;
if (win = true)
{
cout << "YOU WIN! \n\n" << endl;
/*earn = (earn) + Omoney;*/
cout << "You earned: \n" << earn;
Tmoney = earn + (Omoney - bet);
cout << "\nTotal money: \n" << Tmoney;
}
}
else if (bet <= 10)
{
lose = true;
if (lose = true)
{
cout << "You Lose!\n\n\n" << endl;
int Mlose= loseM + bet;
cout << "You lost: \n" << Mlose;
Tmoney = loseM + (Omoney - bet);
cout << "\nTotal money: \n" << Tmoney;
cout << "\n\n\n\n";
Omoney = Tmoney;
main();
}
}
cin.get();
cin.get();
return 0;
}
Use a for loop instead of calling main() again. When you call main(), the local variables are re-initialized.
Alternatively, make the variables global scope (declare them outside of main()).
Read from user "start money" before the loop, and then inside the loop read the bet and do something with the bet. I guess the loop should repeat reading the bets until the user runs out of money.