Im trying to create a number guessing game where the user enters number integers they want to guess and the range of those integers 1 to (m). Then the computer randomly generates numbers in that range for the user to guess. The user guesses until they get all the numbers correct For example:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter guess: 2 3 1 4
3 of your guesses are correct. Guess Again
Enter guess: 2 3 1 6
Correct. Would you like to play again.
The Output I get right now is:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter your guesses for the 4 in the range from 1 to 6 that you have selected: 2 3 1 4
There are three files for this game.cpp, game.h, and driver.cpp. Please let me know if you find anything else wrong with my code. This is my 1st program I have written in C++.
//game.cpp
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
#include <vector>
//---------------------------------------------------------------------------------------------
// generateNumbers: Fucntion to generate numbers between 1 to (m) and
// generate as many has user wanted.
// n: the amount of integers
// m: the max number the user wants
// numbers: returns the numbers generated by the computer
//---------------------------------------------------------------------------------------------
std:: vector<int> Game::generateNumbers(int n, int m) {
// Declare array size to generate random numbers based on what is between 1 to (m)
std::vector<int> random_numbers;
int numbers;
// Randomly generate n intgers between 1 to (m)
for (int i = 0; i < n; i++) {
numbers = (rand() % m) + 1;
random_numbers.push_back(numbers);
}
return random_numbers;
}
//-----------------------------------------------------------------------------------------------
// guessingGame: See's how many numbers the user got to correct until they win the game.
// n: the amount of integers
// m: the max number the user wants
//-----------------------------------------------------------------------------------------------
void Game::guessingGame(int n, int m) {
// Declare variables
std::vector<int> pointer;
int correct_answers = 0;
// Set inputGuess equal to a vector which is teh size of n
std::vector<int> inputGuess;
inputGuess.resize(n);
pointer = generateNumbers(n, m);
// Get user guesses integers
for (int i = 0; i < n; i++) {
std::cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (pointer[i] == inputGuess[j]) {
correct_answers++; //counts how many numbers the user got correct
}
}
}
}
// driver.cpp
#include <iostream>
#include "Game.h"
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iomanip>
#include <vector>
int main()
{
//Declare variables
Game guess;
int n; // number of integers
int m; // max value for integers
int guesses;
std::vector<int> userNumbers;
std::srand(static_cast<unsigned int>(time(nullptr))); // Intialize random number
// Prompt the user to enter integers and range
// Have user enter number of integers they want
std::cout << "Enter the Number of the Integers (n): ";
std::cin >> n;
// Have user enter the range if integers between 1 to m
std::cout << "Enter the Number of Each Integers from 1 to (m): ";
std::cin >> m;
// guesses from user are not correct then user needs to keep guessing
while (userNumbers.size() != n) {
std::cout << "Enter your guesses for the " << n << " " << "in the range from 1 to " << m << " " << "that you have been selected: ";
for (int i = 0; i < n; i++) {
userNumbers.push_back(n);
guess.guessingGame(n,m);
}
}
// If the user has guessed the correct numbers and would like to play again
if (userNumbers.size() == n) {
std::cout << "You are correct! Play Again?";
}
// If numbers guessed not correct then display how many are correct
else {
std::cout << sizeof(userNumbers) << "of your guesses are correct." << std::endl;
}
};
// game.h
#include <vector>
class Game {
public:
// Get what numbers the users have guessed are correct
std::vector<int> getNumbers() {
return correct_number;
}
// Generate random numbers between the range set by user
std:: vector<int> generateNumbers(int n, int m);
// Begin the guessing game
void guessingGame(int n, int m);
private:
std::vector<int> correct_number; // numbers that are correct
std::vector<int> input_guess;
};
The line
inputGuess.push_back(n);
adds only one element, but you are using n elements here:
// Get user guesses integers
for (int i = 0; i < n; i++) {
std::cin >> inputGuess[i];
}
Therefore an out-of-range access happens when n is larger than 1.
To set the number of elements to n, you should use resize() instead like this:
inputGuess.resize(n);
Related
I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5.
But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size.
Then, to get the inputs, I use the for loop and insert them to the array. Let's say first input is 10, then array[0] must be 10 and so on.
The problem is, how do I subtract them? I have two options:
The first element of the array (array[0]) will subtract the next element (array[1]) right after the user input the second element, and the result (let's say it's int x) will subtract the next element (array[2]) after the user input it and so on.
I'll have the user input all the numbers first, then subtract them one by one automatically using a loop (or any idea?) *These elements thing refer to the numbers the user input.
Question: How do you solve this problem?
(This program will let the user input for as much as they want until they type count. Frankly speaking, yeah I know it's quite absurd to see one typing words in the middle of inputting numbers, but in this case, just how can you do it?)
Thanks.
Let's see my code below of how I insert the user input into the array.
string input[100];
int arrayInput[100];
int x = 0;
for (int i = 0; i >= 0; i++) //which this will run until the user input 'count'
{
cout << "Number " << i+1 << ": ";
cin >> input[i];
arrayInput[i] = atoi(input[i].c_str());
...
//code to subtract them, and final answer will be in int x
...
if (input[i] == "count")
{
cout << "Result: " << x << endl;
}
}
You can/should use a dynamic sized container like std::vector as shown below:
#include <iostream>
#include <vector>
int main()
{
int n = 0;
//ask user how many input he/she wants to give
std::cout << "How many elements do you want to enter: ";
std::cin >> n;
std::vector<int> vec(n); //create a vector of size n
int resultOfSubtraction = 0;
//take input from user
for(int i = 0 ; i < n ; ++i)
{
std::cin >> vec.at(i);
if(i != 0)
{
resultOfSubtraction-= vec.at(i);
}
else
{
resultOfSubtraction = vec.at(i);
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
Execute the program here.
If you want a string to end the loop then you can use:
#include <iostream>
#include <vector>
#include <sstream>
int main()
{
std::vector<int> vec;
int resultOfSubtraction = 0, i = 0;
std::string endLoopString = "count";
std::string inputString;
int number = 0;
//take input from user
while((std::getline(std::cin, inputString)) && (inputString!=endLoopString))
{
std::istringstream ss(inputString);
if(ss >> number)
{
vec.push_back(number);
if(i == 0)
{
resultOfSubtraction = number;
}
else
{
resultOfSubtraction-= number;
}
++i;
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
I am new to C++, but this picture here is the goal of my program.
This is what I need my input/output to look like:
--- INPUT ---
The first line of standard input contains an integer 1 ≤ C ≤ 50, the number of test cases.
C data sets follow. Each data set begins with an integer, N, the number of people in the class (1 ≤ N ≤ 1000).
N integers follow, separated by spaces or newlines, each giving the final grade (an integer between 0 and 100) of a student in the class.
--- OUTPUT ---
For each case you are to output a line giving the percentage of students whose grade is above average, rounded to exactly 3 decimal places.
This is the code that I currently have:
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using std::vector;
void aboveAverage(int testCases) {
// initialize number of students for vector size
int numOfStudents;
// initialize a vector to hold grades
vector<int> grades;
// for # of testCases, recieve # of students per test case
for(int i = 0; i < testCases; i++) {
std::cout << "Num of Students: ";
std::cin >> numOfStudents;
// per test case, recieve grade per student and push into vector
for(int j = 0; j < numOfStudents; j++) {
int grade1;
std::string grade;
// debug statement
std::cout << "Enter grades: ";
std::getline(std::cin, grade);
grade = int(grade1);
grades.push_back(grade1);
}
}
// sum the vector array and intitialize above average threshold
int sum = std::accumulate(grades.begin(), grades.end(), 0);
// debug statement
std::cout << "Sum = " << sum << std::endl;
int threshold = sum / numOfStudents;
// initialize a counter and based on threshold get the # of elements that
// meet that criteria
int counter = 0;
for(int j = 0; j < numOfStudents; j++) {
// if the grade is larger than the threshold, add to counter
if(grades[j] > threshold) {
counter += 1;
}
}
// get the percentage of those above average and print it out
float percentage = (counter / numOfStudents) * 10;
std::cout << std::setprecision(3) << std::fixed << percentage << std::endl;
}
int main() {
int testCases;
// debug statement
std::cout << "# of Test Cases: ";
std::cin >> testCases;
aboveAverage(testCases);
return 0;
}
The code as a whole runs "fine", I guess you could say. Just no errors in the compiler that yell at me at least. I just cannot, for the life of me, figure out how to set it up exactly like it should for the input. I think I complicated my life with the vector, although it seems easier to me this way. I think I'm close. Hopefully I am!
I'm trying to create a number guessing game where the user enters number integers they want to guess and the range of those integers 1 to (m). Then the computer randomly generates numbers in that range for the user to guess. The user guesses until they get all the numbers correct For example:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter guess: 2 3 1 4
3 of your guesses are correct. Guess Again
Enter guess: 2 3 1 6
Correct. Would you like to play again.
The Output I get right now is:
Enter number integers: 4
Enter the range of those integers from 1 to (m): 6
Enter your guesses for the 4 in the range from 1 to 6 that you have selected: 2 3 1 4
Then after you enter the guesses nothing else happens with the program. I'm confused on why the game is not saying how many guesses where correct.
I don't understand what I'm doing wrong to get this output. I'm also getting no warnings or errors from my code.
There are three files for this game.cpp, game.h, and driver.cpp. Please let me know if you find anything else wrong with my code. This is my 1st program I have wrote in C++.
//game.cpp
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
using namespace std;
//---------------------------------------------------------------------------------------------
// generateNumbers: Fucntion to generate numbers between 1 to (m) and
// generate as many has user wanted.
// n: the amount of integers
// m: the max number the user wants
// numbers: returns the numbers generated by the computer
//---------------------------------------------------------------------------------------------
int*Game:: generateNumbers(int n, int m) {
// Intialize random number
srand(static_cast<unsigned int>(time(NULL)));
// Declare array size to generate random numbers based on what is between 1 to (m)
int* numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = (rand() % m) +1;
cin >> numbers[i];
}
return numbers;
}
//-----------------------------------------------------------------------------------------------
// guessingGame: See's how many numbers the user got to correct until they win the game.
// n: the amount of integers
// m: the max number the user wants
//-----------------------------------------------------------------------------------------------
void Game::guessingGame(int n, int m) {
int* p;
int sum = 0;
// Call the generateNumber function
generateNumbers(n, m);
// Declare array based on user guesses
inputGuess = new int[n];
p = generateNumbers(n,m);
// Loop for User guesses for the integers
for (int i = 0; i < n; i++) {
cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (p[i] == inputGuess[j]){
sum++;
break;
}
}
}
}
------------------------------------------------------------------------------
//driver.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main()
{
//Declare variables
Game guess;
int n;
int m;
int userNumbers = guess.getNumbers();
// Prompt the user to enter integers and range
// Have user enter number of integers they want
cout << "Enter the Number of the Integers (n): ";
cin >> n;
// Have user enter the range if integers between 1 to m
cout << "Enter the Number of Each Integers from 1 to (m): ";
cin >> m;
// guesses from user are not correct then user needs to keep guessing
while (userNumbers != n) {
cout << "Enter your guesses for the " << n << " " << "in the range from 1 to " << m << " " << "that you have been selected: ";
cin >> userNumbers;
guess.guessingGame(n, m);
}
// If the user has guessed the correct numbers and would like to play again
if (sizeof(userNumbers) == n) {
cout << "You are correct! Play Again?";
}
// If numbers guessed not correct then display how many are correct
else {
cout << sizeof(userNumbers) << "of your guesses are correct." << endl;
}
};
---------------------------------------------------------------------------------
//game.h file
class Game{
public:
// Get what numbers the users have guessed are correct
int getNumbers() {
return number;
}
// Generate random numbers between the range set by user
int* generateNumbers(int n, int m);
// Begin the guessing game
void guessingGame(int n, int m);
private:
int number; // numbers that are correct
int* randomNumbers; // random numbers generated
int* inputGuess; // users guesses
};
There are lots of issues in your code.
srand should not be called each time you want to roll random numbers, but only once (eg in main)
rand is of poor quality. In addition to that, distributions obtained via % are usually not uniform (suppose largest random number is ...108 then %10==9 will have one count less than %10 == i). Take a look at <random> if you need better randomness.
inputGuess = new int[n]; for dynamic arrays is problematic. When a class manages a resource (eg a dynamically allocated array) it must follow the rule of 3/5 or it must be considered broken (in particular, copying your Game will cause problems). Prefer the rule of 0 (same link) when possible and use std::vector instead.
also because of inputGuess = new int[n];, your code has lots of memory leaks. If you really do use new you must delete anything that was created via new. Here a vector is the right choice, other uses of new are covered by smart pointers.
The logic of the code is difficult to decipher, mainly because you seem to confuse int with arrays and 2d arrays of ints.
I could probably continue the list, but anyhow I suggest you to start from scratch. You wrote to much code at once and now are faced with lots of issues. Try to test more. Make a plan of what you want to implement, write a test (that can only fail for now), then write the code that makes the test pass. In this way you always have to deal with at most one or two problems, not all at once.
To give you only a rough sketch of how your code could look like with std::vector:
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iostream>
#include <algorithm>
struct Game {
Game(size_t num,int min,int max){
for (size_t i=0;i<num;++i) hiddenNumbers.push_back( rand()%(max-min) + min);
}
void reveal(){
for (const auto& n : hiddenNumbers) std::cout << n << " ";
std::cout << "\n";
}
bool guess(int x){
--num_guesses;
auto it = std::find(hiddenNumbers.begin(),hiddenNumbers.end(),x);
if (it == hiddenNumbers.end()) return false;
hiddenNumbers.erase(it);
return true;
}
bool has_more_guesses(){ return num_guesses > 0; }
int remaining() { return num_guesses; }
private:
int num_guesses = 5;
std::vector<int> hiddenNumbers;
};
int main(){
srand(static_cast<unsigned int>(time(NULL)));
Game g{10,2,5};
while (g.has_more_guesses()) {
bool correct = g.guess(2);
if (correct) std::cout << "Yay. Guessed numbeer was corerct! \n";
std::cout << "you have " << g.remaining() << " remaining guesses\n";
std::cout << "spoiler altert! Secret numbers are: ";
g.reveal();
}
}
Each game has maximum 5 trials. If you still continue to call guess the counter num_guesses will get negative. You might want to fix that. When a number is found guess returns true and the number is erased from the private vector.
Possible output:
Yay. Guessed numbeer was corerct!
you have 4 remaining guesses
spoiler altert! Secret numbers are: 3 4 2 2 3 4 4 2 3
Yay. Guessed numbeer was corerct!
you have 3 remaining guesses
spoiler altert! Secret numbers are: 3 4 2 3 4 4 2 3
Yay. Guessed numbeer was corerct!
you have 2 remaining guesses
spoiler altert! Secret numbers are: 3 4 3 4 4 2 3
Yay. Guessed numbeer was corerct!
you have 1 remaining guesses
spoiler altert! Secret numbers are: 3 4 3 4 4 3
you have 0 remaining guesses
spoiler altert! Secret numbers are: 3 4 3 4 4 3
I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
EDIT:
"Improved" code:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}
When you get to the 47th value, the numbers go out of int range. The maximum int value is 2,147,483,647 and the 46th number is just below at 1,836,311,903. The 47th number exceeds the maximum with 2,971,215,073.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for loop that you have. Vectors start with 0, and so by having number<=length; the range+1 element will be called. The range only goes up to length-1.
You are encountering integer overflow, meaning that you are trying to calculate a number that is outsize of the bounds of INT_MAX and INT_MIN. In the case of an unsigned number, it just overflows to zero and starts over, while in the case of a signed integer, it rolls over to INT_MIN. In both cases this is referred to as integer overflow or integer wraparound.
You could put a band-aid on the solution by using long long int (likely 64-bits on most modern systems) instead of int for your primitive data type, or you could use a better approach like a library that supports (almost) arbitrarily long data types, like libBigInteger.
References
Integer Overflow, Accessed 2014-03-04, <http://en.wikipedia.org/wiki/Integer_overflow>
C++ Big Integer Library, Accessed 2014-03-04, <https://mattmccutchen.net/bigint/>
The limits.h Header File, Accessed 2014-03-04, <http://tigcc.ticalc.org/doc/limits.html>
This is my solution to calculating BIG fibonacci numbers
// Study for algorithm that counts n:th fibonacci number
#include <iostream>
#include <cstdlib>
#include "boost/multiprecision/cpp_int.hpp"
#define get_buffer(a) buffer[(a)%2]
#define BIG boost::multiprecision::cpp_int
int main(int argc, const char* argv[])
{
// atoi returns 0 if not integer
if(argc != 2 || atoi(argv[1]) < 1){
std::cout << "You must provide one argument. Integer > 0" << std::endl;
return EXIT_SUCCESS;
}
// ring buffer to store previous two fibonacci number, index it with [i%2]
// use defined function get_buffer(i), it will do the magic for you
BIG buffer[2]={ 1, 1 };
// n:th Fibonacci
unsigned int fn = atoi(argv[1]);
// count loop is used if seeked fibonacci number is gt 2
if(fn > 2){
for(unsigned int i = 2; i < fn; ++i){
get_buffer(i) = get_buffer(i-1) + get_buffer(i-2);
// get_buffer(i-1) + get_buffer(i-2) == buffer[0] + buffer[1]
// if you want to print out every result, do it here
}
}
// Result will be send to cout
std::cout << "Fibonacci[" << fn << "] is " << get_buffer(fn-1) << std::endl;
return EXIT_SUCCESS;
}
I have an assignment that simulates a dice game. As part of the program, the user enters the number of dice to roll and the number of times to roll them. If the user rolls 4 dice, the program should sum the 4 values, store the result in an array, then redo the program the number times defined by the user. The main code and the function prototypes were defined by our tutor and cannot be amended. We have to write the function.
In Step 3 of the main, there are two for loops. The inner for loop calls the function in question. A 2D array rollSums[][] is assigned to the result of the function. This array is to be used in another function. I can't figure out how to populate the 2D array correctly from the function. The code and my attempt at the function is below:
#include <iostream>
#include <iomanip>
#include <cstdlib> // needed for functions srand() and rand()
#include <ctime> // needed for function time()
#include <cmath> // needed for sqrt()
using namespace std;
const int MAXNUMTOROLL=10;
const int MAXROLLS=100;
int rollDice(int diceVals[], int numToRoll);
int main()
{
int sum;
int rollSums[MAXNUMTOROLL][MAXROLLS];
int diceVals[MAXROLLS];
double mean[MAXNUMTOROLL], std[MAXNUMTOROLL];
int numToRoll, numRolls;
srand(time(NULL));
// STEP 1: Ask user to input the maximum number of dice to use:
cout << "Please enter the maximum number of dice to use:" << endl;
do
{
cin >> numToRoll;
} while (numToRoll < 0 || numToRoll > MAXNUMTOROLL);
cout << "Please enter the number of rolls:" << endl;
// STEP 2: Ask user to input the number of rolls to carry out:
do
{
cin >> numRolls;
} while (numRolls < 0 || numRolls > MAXROLLS);
// STEP 3: For k=1 to numToRoll, simulated numRolls rolls of the dice
// and store the sum of the numbers rolled in the array rollSums[][]
for (int k=1;k<=numToRoll;k++)
{
for (int i=0;i<numRolls;i++)
{
rollSums[k-1][i] = rollDice(diceVals, k);
}
}
return 0;
}
int rollDice(int diceVals[], int numToRoll) //function simulating throwing of dice
{
int sum=0;
int i=0;
for(i=0;i<numToRoll;i++)
{
diceVals[i]=1+rand()%6;
sum=sum+diceVals[i];
}
return sum;
}
adohertyd, see my comments in the code sample:
#include <iostream>
#include <iomanip>
#include <cstdlib> // needed for functions srand() and rand()
#include <ctime> // needed for function time()
#include <cmath> // needed for sqrt()
using namespace std;
const int MAXNUMTOROLL=10;
const int MAXROLLS=100;
const bool show_debug = true;
int rollDice(int diceVals[], int numToRoll);
int main()
{
int roll_Sums[MAXNUMTOROLL];
int diceVals[MAXROLLS];
//double mean[MAXNUMTOROLL], std[MAXNUMTOROLL];
int numDice, numThrows;
//Initialize random number generator with the current time
srand(time(NULL));
// STEP 1: Ask user to input the maximum number of dice to use:
cout << "Please enter the maximum number of dice to use:" << endl;
// STEP 2: Validate number of dice input
do
{
cin >> numDice;
} while (numDice < 0 || numDice > MAXNUMTOROLL);
//STEP 3: Ask user to input the number of times to throw each dice
cout << "Please enter the number of rolls:" << endl;
// STEP 4: Validate number of throws input
do
{
cin >> numThrows;
} while (numThrows < 0 || numThrows > MAXROLLS);
cout << "\n\nThrowing Dice Now...\n\n";
// STEP 5: Roll the dice
//The loop deals with each dice
for (int diceCount = 0; diceCount < numDice; diceCount++)
{
//The function call deals with all the throws per dice
//Note: roll_Sums array didn't need to be two dimensional,
// also, rollDice gets passed diceVals[] by value and the number of throws to execute
roll_Sums[diceCount] = rollDice(diceVals, numThrows);
//Debug output
if(show_debug)
{
//Since roll_Sums is zero based, add one to the visible index so the user doesn't get confused :P
cout << "Roll Sum for dice #" << diceCount + 1 << ": " << roll_Sums[diceCount] << endl << endl;
}
}
return 0;
}
//rollDice() returns the sum of all the dice rolls it performed
int rollDice(int diceVals[], int numToRoll)
{
int sum=0;
for(int i=0;i<numToRoll;i++)
{
//Get your random dice rolls
diceVals[i]=1+rand()%6;
//Debug output
if(show_debug)
{
cout << "Dice Roll # " << i+1 << ": " << diceVals[i] << endl;
}
//Accumulate your value, e.g. "sum"
sum += diceVals[i];
}
return sum;
}