Okay, im just about done with my exercise and stuck on how to get each dice to roll their own individual randomly generated number. The program does in fact roll random numbers, it's just every time you re-roll both dice always roll the same exact numbers. And this simple but yet head scratching problem occurred, for some reason i'm also having
cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;
I was also told by a class mate that my faceValue was an illegal value and should be set to a legal value. I didn't quite get what he meant and I'm sure it'll knock off (not a lot) a few of my grade.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
class PairOfDice
{
private:
int diceOne;
int diceTwo;
int score;
int faceVaule;
public:
PairOfDice(){
srand(time(NULL));
roll();
}
void roll(){
diceOne = (rand() % 6) + 1;
diceTwo = (rand() % 6) + 1;
setdiceOne(diceOne);
setdiceTwo(diceTwo);
}
void setdiceOne(int value){
faceVaule = value;
}
int getdiceOne(){
return faceVaule;
}
void setdiceTwo(int value){
faceVaule = value;
}
int getdiceTwo(){
return faceVaule;
}
void totalScore(){
score = diceOne + diceTwo;
}
void display(){
cout << "The first Dice rolled a " << getdiceOne() << " ." << endl;
cout << "The second Dice rolled a " << getdiceTwo() << " ." << endl;
// adding both dices gives an: No operator " < < " matches these operands
cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
PairOfDice game;
game.roll();
game.display();
game.totalScore();
return 0;
}
First of all: you roll two dice, store the results in dice1 and dice2, but then you send those values to two functions that put the value into a variable called faceValue.
It is logical that getting the value back will return only the second dice value, because that's what you last entered in faceValue.
That is why the same values are shown for both dice.
Now for the error: your totalScore function returns a void while the << operator expects some kind of type.
The totalScore function adds the two dice (correct values by the way) and puts the result in score, but nowhere, the value in score is returned.
Your code is really messy. You shouldn't have one member variable (faceValue) holding a copy of two different values. You shouldn't have this member at all. Just use the diceOne and diceTwo values.
When the values are set ( = rand() % 6 + 1 ), they should not be set again by calling the set-function: Either create a correct set-function (because this one isn't correct) and put the random as a parameter in there, or set the member variable diceOne and diceTwo directly in the constructor as you already do. Don't do both.
When returning the sum of the two dice, why not just return this sum (hint: the function totalScore should return something of the int-type). Why are you putting the summed result into a member variable? There is no need for that.
I could post the corrected code here, but it seems that you really have to learn this yourself.
Edit: And by the way: as stated above, learn to use the debugger. You will soon discover that the things I am telling you are correct. You will notice that faceValue first gets the value of diceOne and then the value of diceTwo, never getting the diceOne value back.
Related
Trying to write a program displaying the average temperature in 24 hours, by the user typing in the temperature each hour. However, I'm just getting this error in code blocks:
warning: 'totalTemp' may be used uninitialized in this function [-Wmaybe-uninitialized]|.
and the console is just black when ran and not displaying anything.
#include <iostream>
using namespace std;
int main(void)
{
int i = 0;
while(i <= 24);
int newTemp;
int totalTemp;
{
cout << "Input temperature for the hour " << i << ":";
cin >> newTemp;
totalTemp = totalTemp + newTemp;
i++;
cout << "The average temperature for the day is " << totalTemp/24 << " degrees";
}
return (0);
}
How do I initialize it? and what is making my code not appear in the console when I'm trying to use cout?
How do I initialize it?
int totalTemp = 0;
and what is making my code not appear in the console when I'm trying to use cout?
while(i <= 24);
This is an infinite loop with an empty body. Infinite loops without observable side effects are undefined behavior. The compiler is allowed to produce the same output for your code as it would for int main() {}. You probably want while( i<=24) { .... Or rather use a for loop when the number of iterations is fixed.
Moreover, totalTemp/24 is using integer arithmetics. Maybe thats what you want, but more likely you want totalTemp/24.0. And also very likely you want to print the average outside of the loop instead of printing it in every iteration.
Im doing an excercise sheet to get an understanding of functions and I am currently working on the following question.
Write function prototypes for each of the following:
A function HasValue that may be passed a reference to an array, the size of the array and a
search value. The function should return true if the search value exists in the array
In my code I have sent the contents of the array, the array size and the value to be searched in the array to the bool function.
In the function I compared the value to each element of the array using a for loop.
I then created a variable count in the function that will be incremented if the value matches any element in the array.
I then used an if else statment to return true if count is greater than 0 and false if count is equal to 0. The problem is however that the function is only returning true thus the output will always be "this number appears in the array"
Logically these steps seem correct to me but obviously there is a flaw somewhere that I cant see. I presume its just I do not have a decent understanding of Bool functions yet but if someone could explain where and why I'm going wrong it would be greatly appreciated in my learning process to understanding functions and c++.
#include <iostream>
#include <iomanip>
#include "stdafx.h"
using namespace std;
bool HasValue(int Array[], int size, int Value);
int main()
{
int value;
int Array[10]{ 3,5,6,8,9,1,2,14,12,43 };
cout << "enter value you wish to search for in array " << endl;
cin >> value;
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
return 0;
}
bool HasValue(int Array[], int size, int Value)
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (Value == Array[i])
{
count++;
}
}
if (count > 0)
{
return true;
}
else
return false;
}
You test code is the problem
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
This ignores the return value of HasValue and always prints "This number appears in the array".
HasValue(Array, 10 , value);
This line of code executes the function but ignores the returned value. When a function returns a value, you need to assign it to a variable:
bool result = HasValue(Array, 10 , value);
Then if (true) does not have any reference to the returned value. The true inside the if will cause the first cout to always print. You will never see the output from the else. But once you have the return value in a variable, you can use it in the if:
if(result)
You can reduce this all to one line of code, if you want:
if(HasValue(Array, 10 , value))
Now the if statement will directly test the return value from HasValue(). In this particular case, combining the code into a single line seems reasonable. You must be careful doing this, though. When you combine too much into a single line, the code becomes more difficult to debug. You will need to find a balance between readability and convenience as you continue learning how to program.
I'm working on a simple "addition questions" program for my intro to C++ class. My instructor uses a test driver to grade our code. The test driver first runs the program using his code, and then runs my function and compares the two.
In this code, we're supposed to generate random numbers to give the user simple addition problems. They enter the answer and the program keeps track of how many they got correct, and returns the number of correct answers to the main function.
As I understand it, srand() will generate the same list of numbers if the seed is the same. The problem I'm having is even though I put srand(seed) at the top of my function, the successive numbers generated by each rand() call are still different. As I understood it, if you recall srand with the same seed, it will reset the number generator and give you the same chain of numbers from rand().
Because he uses a test driver to grade, the driver is telling me almost all of my results are wrong, but it's because the driver does not actually calculate my random generated numbers, it just looks for the same answers as what he got in his version of the program. So the problem is for some reason calling srand(seed) is not using the same numbers.
This could be a problem with his driver, if it is sending a different number to my function for seed than he used, but it could also be that I put srand() in the wrong place, or I'm not using it correctly.
Can anyone confirm if the use of srand(seed) in my code would reset and use the same numbers given that seed value is the same?
Here's my function:
int correct = 0; // initialize global variable to return correct answers
// define the additionQuestions function.
int additionQuestions(int largest, int problemCount, int seed)
{
srand(seed); // initialize the random generator to the same seed used in test driver
int gen1, gen2, answer;
bool quitting = false;
// generate problems
for (int count = 0; count < problemCount && (!(quitting)); count++)
{
gen1 = rand() % largest;
gen2 = rand() % largest;
cout << "How much is " << gen1 << " plus " << gen2 << "? ";
cin >> answer;
if (answer == -1) // check for sentinel of -1
{
cout << endl << " You entered -1; exiting...";
quitting = true;
}
else // check if the user's answer is correct.
{
cout << endl << " You said " << gen1 << "+ " << gen2 << " = " << answer << ".";
if (answer == gen1 + gen2)
{
cout << " Very good!" << endl;
correct += 1;
}
else
{
cout << " No. Sorry, the correct answer is " << gen1 + gen2 << "." << endl;
}
}
} // end of for loop.
return correct; // return the number of correct answers to the main function
}
Before you write to your professor....
Your using implicit type casting from 'int seed' to 'srand(unsigned int seed)' which could cause issues when the test driver tries to test your program with a seed larger than ~2.1M.
Good luck.
I don't understand recursive functions.
I wrote this code to help me but i don't understand why it works the way it does.
It prints backwards the steps from 0 to the number n/2 i input but don't know what makes it print every step it skipped from low to high because it went recursive. I am close but not yet there...
#include <iostream>
#include <conio.h>
using namespace std;
int recursiv(int );
int times;
int main(){
int x;
cout<<"Imput number\n";
cin>>x;
recursiv(x);
getch();
return 0;
}
int recursiv(int x){
times++;
if(x)
recursiv(x/2);
cout<<"We are now at "<<x/2<<endl;
if (!x)
cout<< "We reached "<<x<<" but it took "<<times-1<< " steps\n";
return 0;
}
When you are dealing with recursion you have to understand two main part of the function code: the one that is executed on the way forward, and the one that is executed on the way back:
void X() {
// way forward
X();
// way back
}
The way forward part is executed while calling the function over and over until the end of the recursion; the way back is executed while coming back from the last call to the first.
void print(int x) {
if (!x) return; // end of recursion
std::cout << x << " ";
print(x-1);
}
The above example contains std::cout << x on the way forward which means that the call print(5) will print: 5 4 3 2 1.
void print(int x) {
if (!x) return; // end of recursion
print(x-1);
std::cout << x << " ";
}
The above example moved the actual printing to the way back part of the function which means that the same call print(5) will print: 1 2 3 4 5.
Let's take your function (cleaned up a bit):
int recursiv(int x){
times++;
if(!x) return 0; // split
recursiv(x/2);
cout << "We are now at "<< x / 2 << endl;
return 0;
}
We can distinguish our two parts quite easily. The way forward is:
times++;
if(x) return;
In which we just increment our int parameter times (we just ignore the conditional for the end of recursion here).
The way back is:
cout<<"We are now at "<<x/2<<endl;
return 0;
Which will be executed from the last call to the first one (just like the second version of the example). Therefore taking from the lowest number (the one nearer to 0 because of the end recursion condition) which is the last called before the end of recursion to the first, just like our example.
If i understand your question correctly:
It should print from high to low, but it actually prints from low to high. why is that?
The line cout<<"We are now at "<<x/2<<endl; is after the call for recursion.
so the function calls itself with a smaller amount again and again until it hits the break criteria.
the the function with the smallest amount calls the std::cout, return the second smallest amount does the std::cout and so on until the last one does it.
If you want the result in the other order, move the mentioned line two lines higher, so each iteration echos before calling the child.
example:
int recursiv(int x, int times = 0) {
std::cout << "We are now at " << x/2 << std::endl;
if(x)
return recursiv(x/2, times + 1);
else
std::cout << "We reached " << x << " but it took " << times << " steps" << std::endl;
return 0;
}
Unrelated: Global variables are considered a bad practice. There are use cases for them, this is not one of them. I fixed that within the function.
This is what I have to do:
A teacher has asked all her students to line up single file according to their first name. For example, in one class Amy will be at the front of the line and Yolanda will be at the end. Write a program that prompts the user to enter the number of students in the class, then loops to read in that many names. Once all the names have been read in it reports which student wourld be at the front of the line and which one would be at the end of the line. You may assume that no two students have the same name. Input Validation: Do not accept a number less than 1 or greater than 25 for the number of students.
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int StudentNum;
cout << "How many student are in the class?\n";
cin >> StudentNum;
char sname[StudentNum + 1][25];
if (StudentNum < 1 || StudentNum > 25)
{
cout << "Please enter a number between 1-25 and try again\n";
return 0;
}
for (int i = 1; i <= StudentNum; i++);
{
cout << "Please enter the name of student #" << i << endl;
cin >> sname[i];
}
for (int output = 0; output <=StudentNum; output++);
{
cout << endl << sname[output] << endl;
}
system ("pause");
return 0;
}
Am I missing something about arrays??
You cannot create such an array because its length has to be known at compile time (i.e., it cannot be the result of an expression such as StudentNum + 1).
You can solve this issue because by the problem definition you know an upper bound for the array size, so you can use that as a compile time constant.
However, this problem can be solved without using an array at all. Read the wording carefully.
Hint for the solution without arrays: Think of the array as a single piece of paper (variable) with all the names written one after another. Not using an array then means that you have to be able to solve the problem without looking at all the names at once. How would you come to the answer if I only allowed you to see the names one by one?
Another hint: The problem is still solvable if there were several trillion students in the class (with unique names no less), i.e. more than could possibly fit in the computer's memory at any one time.
C++ array dimensions must be known at compile time (ie not dependent on user-entered variables at run-time). Use strings instead:
string sname[25];
If you were using something besides char arrays, you could also use a vector.
Think about what the problem statement is actually asking for. Your program only needs to output the first and last names alphabetically. Do you actually need to store all the names to do that?
Just for fun, here's how I would do it. Don't turn this in unless are ready to explain to your teacher how it works.
struct MinMax {
std::string min;
std::string max;
MinMax& operator+(const std::string& kid) {
if( min.empty() || kid < min) min = kid;
if( max.empty() || kid > max) max = kid;
return *this;
}
};
int main() {
int nKids;
std::cout << "How many students? " << std::flush;
std::cin >> nKids;
std::cout << "Enter students' names, followed by EOF\n";
MinMax mm(std::accumulate(
std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
MinMax()));
std::cout << mm.min << ", " << mm.max << "\n";
}