I've been tasked with creating a very simple random walk program for a C++ class. I wrote it and was fairly sure everything was correct but I am getting this strange bug. From 0 to 10 the steps line up even though the coordinates show that its taking alternating left and right steps.
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
int steps,i,pos=10;
srand(13699);
cout << "Please enter the amount of steps to be taken: ";
cin >> steps;
cout << endl;
for (i=0;i<=steps;i++)
{
if (rand()%2)
pos+=1;
else
pos-=1;
cout << i << ": " << pos-10 << ": " << setw(pos) << "*" << endl;
}
} // main
There is very obviously some sort of pattern here, but for the life of me I can't figure it out... Here is a link to a screenshot of the output if it helps. http://i.stack.imgur.com/USx4U.png Thanks for any help y'all can give!
The answer is not in the code but rather in your interpretation of the output.
When the pos-10 is less than 0 then the area where you print this value is longer (because of the minus sign), then your 'walker' is shifted right a position in the output.
Similar reason when it goes from 9 to 10 it isn't right.
Think about what it means that the colons on the left are not in a straight line.
The "lining up" for i between 1 and 10 makes sense.
Take the first two lines, for example:
When i == 1, you have pos == 10, and the * is printed 10 spaces after the :.
When i == 2, you have pos == 9, and the * is printed 9 spaces after the :.
But because you are printing 0 (one character) in the first line and -1 (two characters) in the second line, the * end up on the same place in each line.
BTW, you are using the same value (13699) for seeding the RNG every time you run your program.
Try using a more "random" value, for example, a time-based one:
srand((unsigned int)time(NULL));
You'll need to #include <time.h> in your source file.
Related
This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
Closed 2 years ago.
I'm a newbie in the programming world, and i've decided to start with C++ code a few days ago as my first programming language.
I just started to read an online course which i'm guiding on (and aply while i'm reading it).
The course in question assigns a serie of small optional exercises, wich go hand in hand with the topic that is being dealt at that moment.
One of this optional exercises is: "Create a program that multiplies two whole numbers in the following way: it will ask the user for a first whole number. If the number that you type is 0, it will write on the screen "The product of 0 by any number is 0". If a number other than zero has been entered, the user will be prompted for a second number and the product of both will be displayed."
How it says, I did my best to coding that program.
The code of what I did is:
#include <iostream>
using namespace std;
int main ()
{
int a;
int b;
int solve;
cout << "Enter a number: ";
cin >> a;
if (a!=0)
{
cout << "Enter another number: ";
cin >> b;
}
if (b!=0)
{
solve = a * b;
cout << "The result of your operation is: " << solve << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
return 0;
}
So, I press F9 to compile, then F10 to run it.
I proceed to testing it.
I put and different number from zero, I put another one. Throws me a multiplication of both. Nice.
I put and different number from zero, I put another one that actually its zero. Throws me the message of "else" order. Nice.
**BUT
I put and number equal to zero, and throws me the message of the "cout" order of "if (b!=0)".**
I didn't really know what I had done wrong, so, I ask for help from a friend who has some more experience than me, and tells me that actually it's nothing wrong. In fact, he proved me sending to me a screen cap of his Dev C++ with my code in it, and how it runs just how it had to be.
Then, I opened an online compiler (https://www.onlinegdb.com/online_c++_compiler#) to get down my doubts, and yes, there runs correctly too.
So, here's my question?
What's the problem? Why that happens?
I have the DevC++ 5.11 TDM-GCC 4.9.2, and I'm using the deafult compiler.
Please, I would like some of help, I feel more comfortable compiling in PC than online, it's more quick.
Thank you anyway for reading until here.enter image description here
The reason why this happens, as #TrebledJ mentioned, is that you've not initialised the variable b. So you can get over this problem just by initialising b to any value of your choice (preferrably 1 or 0 for simplicity). But there's a workaround if you don't want to initialise the values. I would transform your code to something like this:
if (a!=0)
{
cout << "Enter another number: ";
cin >> b;
if (b!=0)
{
solve = a * b;
cout << "The result of your operation is: " << solve << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
}
else cout << "The product of 0 by any number is 0." << endl;
Basically, what I'm doing is, if the value of a after input is 0, I'm not running the part for taking the user input of b.
EDIT
I've seen a few wondering what I am asking for. I haven't written the algorithm for it yet, but after the program runs and outputs the 2 arrays, I need to output how many numbers matched. There is an example of that below. My apologies, I really thought that I made it as clear as possible. Here is the example again.
If the randomly generated array comes up with the numbers 0,1,2,3,4 in that order, and the user inputs into the "player" array the numbers 0,1,4,3,2 in that order, then they matched 2 digits (0 and 1). Basically it's not enough to just have the same numbers anywhere in the array, they must be in the same spot or index. I need to write an algorithm for this, though I have not yet. I'm sure I need a function with a for loop. I'm looking for any tips on how to go about it.
I've seen many iterations of this program on StackOverflow but none have been able to help me out so here I am asking for help.
I have this program that has 2 arrays. In one array that generates 5 random numbers from 0-9, the name is winningDigits. The other array (player) is for 5 numbers the user inputs. The goal of the user is to input 5 numbers and hope they all match with the randomly generated numbers.
I am almost done with the program, my only issue is trying to output how many digits were matched. For digits to match, they must be in the same spot in the player array as the winningDigits array.
For example
If the randomly generated array comes up with the numbers 0,1,2,3,4 in that order, and the user inputs into the "player" array the numbers 0,1,4,3,2 in that order, then they matched 2 digits (0 and 1). Basically it's not enough to just have the same numbers anywhere in the array, they must be in the same spot or index.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
int player[5];
int size = 5;
int count = 0;
cout << "Welcome to Lottery Simulator." << endl << endl;
cout << "Enter 5 numbers ranging from 0-9 one at a time, enter -1 when finished." << endl;
// Loop for user input
cout << "Enter number: ";
cin >> player[count];
while (player[count] != -1)
{
count++;
cout << "Enter number: ";
cin >> player[count];
}
cout << endl;
cout << "Winning Numbers User Numbers" << endl;
cout << "--------------- ------------" << endl;
// Generating random winning numbers
srand(time(0));
int winningDigits[size];
for (int i = 0; i < size; i++) {
winningDigits[i]= rand() % 10;
cout << setw(8) << winningDigits[i] << setw(17) << player[i] << endl;
}
return 0;
}
Now I'm thinking I'll need to make a function with a for loop, but so far I'm stuck. Just in case it wasn't clear enough, I am looking to output how many digits were matched. I hope my example from above will help you all understand what I'm looking for. Sorry, this is only my second post here and I am trying to make everything as clear as possible. Please ask if you need any information or help in understanding what I wrote.
It seems like I always come here to ask silly questions, but here it goes. As of right now I am in my first compsci course and we are learning c++. I've had an extremely basic introduction to c before, so I had thought I'd go above and beyond my current assignment. Now I was doing this just to showboat, I felt like if I didn't practice my previous concepts they would eventually fade. Anyways, on to the problem! I was supposed to write some code that allowed the user to input their initials, and a series of exams. Now this was supposed to accomplish three things: average the exams, print out the entered exams, and print out their initials. Well, what was a simple assignment, got turned into a huge mess by yours truly.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string uInitials;
float avgExam = 0, tExam = 0;
int aExams[10] = {'0'};
int i, nExam = 0, cExam;
cout << "Enter your three initials!";
cin >> uInitials;
do
{
cout << "Enter your exam(s) to be averaged. Enter 0 when complete!\n";
cin >> cExam;
aExams[nExam] = cExam; //I used this before nExam was incremented, in order to get nExam while it was '0' That way the first exam score would be properly saved in the first space
nExam++;
tExam += cExam; //This is just to add all the exams up to later calculate the average
}
while(cExam != 0);
avgExam = tExam/(nExam - 1); //subtracted '1' from nExams to remove the sentinel value from calculations.
cout << "The average for initials: " << uInitials << " is: " << avgExam << endl;
cout << "This average was obtained using the following scores that were entered: \n";
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
return 0;
}
The previous is my code, and the problem is that I'm getting output errors where it adds two '0's when I print out the list of entered exams. Also I feel like I made the whole do{}while() loop one huge clunky mess, so I'd like to refine that as well. If anyone could assist this poor, ignorant, beginner I would greatly appreciate it. Thank you for your time!
Some advice that i can give is for example in the 5th line there is no need
to put the 0 between ' ' and not even need to use the assign = operator.
You can initialize the array like this:
int aExams[10]{0};
Which will initialize all elements to 0,but can't be used for other value.
For example you won't have all the elements with value 1 if you write
int aExams[10]{1};
If your intention to initialize all elements in an array is with value other than 0 you can use fill_n(); function.
fill_n(aExams, 10, 1);
The first argument is the name of the array, the second is up-to which element you want to be initialized with the third argument, and the third is the value you want all elements to have.
Do not leave uninitialized variables like in line 6 with cExam and i variables. Initialize it like cExam=0; (copy-assign initialization) or cExam(0); (direct initialization). The latter calls the constructor for int built-in type.
A negative i see in your do-while loop is that you do not make sure that the user will enter under 10 exams,bad things will happen if the user tries to input 15 exams in an array that can hold only 10.
Just change the while to something more like this:
while( cExam != 0 && (nExam<10) );
You can also write the first two lines of the do-while loop outside the loop.
It is needed only once to tell the user that to stop the loop he/she needs to enter 0. There is no need to tell them this on every iteration plus that you will have a good performance benefit if you put those two lines outside the loop.
Look here how i would write the code and ask if you have any questions.
http://pastebin.com/3BFzrk5C
The problem where it prints out two 0's at the end of your code is a result of the way you wrote your for loop.
Instead of:
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
Use:
for (i = 1; i < (nExam); i++)
{
cout << aExams[i - 1] << endl; //Used a for loop to prevent redundancy
}
I'm still very new to C++ still and decided to make a fibonacci sequence. It worked (Woo!) but it doesn't work as well as I would like it to.
what I mean by that is say for example I told my program to count the first 10 terms of the sequence I will get
"0, 1, 1" and then I have to press enter for each additional number until it hits ten in which case the program returns 0 and ends.
How do I get the program to display all the numbers I want to without hitting enter for each additional one?
Here is my script:
#include <iostream>
using namespace std;
int main()
{
int FibNum;
cout << "How many numbers of the Fibonacci Sequence would you like to see? \n\n";
cin>> FibNum;
cin.ignore();
int a = 0;
int b = 1;
int c = 2;
cout << "Fibonacci Sequence up to " << FibNum << " terms.\n\n";
cout << a << "\n" << b << "\n";
for (int c = 2; c < FibNum; c++) {
int d = a + b;
cout << d;
cin.ignore();
a = b;
b = d;
}
}
Thanks in advance for any help!
P.s. Also if you notice anything terrible I'm doing please feel free to correct me, I'm very aware I'm probably doing a lot wrong, I'm just trying to learn. :]
A few things:
1) Remove int c = 2; as you're re-defining c inside the for loop.
2) Drop the line cin.ignore();: in your for loop: that will fix your "enter" problem; that line waits for some input then ignores it.
3) Put some white space in your output: e.g. cout << d << ' ' so your numbers are separated.
4) [Acknowledge vincent_zhang] Consider moving to uint64_t as your data type for a, b, and d. This is a standard type in C++11. It's a 64 bit unsigned integer type; adequate for a large number of terms.
and a small thing, bordering on personal opinion,
5) Use ++c instead of c++ as the former will never run slower as, conceptually at least, post-increment has to take a copy of the original value.
Besides the previous answers,
To better format the output, add white space by changing this
cout << d;
to
cout << d << " ";
You may want to change the type of a, b and d from int to double to prevent overflow.
(If you let FibNum=100 in your code, you should be able to observe overflow, meaning that you are going to get some incorrect numbers toward the end of the sequence.)
Move cin.ignore() out of the loop then you dont need to enter to print all the 10 numbers of Fibonacci series
when I am trying to run this snippet of code I am getting some malfunctions I have not been able to pinpoint the cause of. The first two "cout" lines display the numbers 7 and 3, however, the last "cout" line displays numbers ranging from 50-60 usually (At the moment when I run it I get 55 and 51, which seems to somehow correlate a bit with the numbers I am trying to read). As far as I can tell from some googling and the books I have at hand this should be valid, but there's obviously something I am missing. Thank you for your time.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "73";
int one=0, two=0;
cout << text.at(0) << endl;
cout << text.at(1) << endl;
one = text.at(0);
two = text.at(1);
cout << one << endl << two << endl;
return 0;
}
the program functions correctly: text.at() returns a char, which you implicitly convert to an int. Then you print the value of that int, which are respectively 55 for "7" and 51 for "3" (look here).