The code I am currently working on is a random walker. The code represents a person taking a step in any random direction (up,down,left,right), then the new location is printed out respectively. In the beginning the user is prompted to enter any amount of steps or how many times the loop should be iterated. The goal of the code is to calculate the squared distance between (0,0)initial and (x,y)final. The distance should be equal to (xx)+(yy) because the initial position that would normally be subtracted is (0,0). The issue or semantic issue I am running into is with the distance calculation. The calculation is not always using the correct x or y value. For example if the final location was (0,-4), somehow x = -1, therefore the distance equals 17 instead of 16. This first example is in image 1. Image 2 is another run for the code. Any help or tips would be greatly appreciated, here is the code:
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N;
cout << "Please enter N amount of steps, and for NetBeans users press
'enter' twice." << endl;
cin >> N;
cout << "% RandomWalker " << N << endl;;
int r;
srand( time(0));
int x = 0;
int y = 0;
for(int i = 0; i <= N; i++) {
cout << "(" << x << ", " << y << ")" << endl;
r=rand()%4;
if (r == 0 )
x++;
else if (r == 1 )
x--;
else if (r == 2 )
y++;
else if (r == 3 )
y--;
}
int d = (x*x)+(y*y);
cout << "the distance equals: " << d << endl;
cout << endl;
cout << "x equals before: "<< x << endl;
x = (pow(x,2));
cout << "x equals after squaring: "<< x << endl;
cout << endl;
cout <<"y equals before: " << y << endl;
y = (pow(y,2));
int sum = x + y;
cout <<"y equals after squaring: " << y << endl;
cout << endl;
cout << "x+y after squaring equals: " << sum << endl;
}
for(int i = 0; i <= N; i++)
Since you are starting from 0, the condition should be i < N.
Next issue, is int d = (x*x)+(y*y); The distance formula is
So the initialization should be
int d = sqrt((x * x) + (y * y));
Also what is the point of squaring the x and y values at the end?
You are printing the position BEFORE it is changed based on the value of r. So the last value that's printed out is not the actual final value of x and y, but the one of one step earlier. That's why you're getting unexpected distance.
Sorry for the delayed response, I figured out what I had to do. The object of the assignment was to print out each location and find the squared distance at the end of the loop. Here was the solution for anyone interested.
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N;
cout << "Please enter N amount of steps, and for NetBeans users press
'enter' twice." << endl;
cin >> N;
cout << "% RandomWalker " << N << endl;;
int r;
srand( time(0));
int x = 0;
int y = 0;
cout << "(" << x << ", " << y << ")" << endl;
for(int i = 1; i <= N; i++) {
r=rand()%4;
if (r == 0 )
x++;
else if (r == 1 )
x--;
else if (r == 2 )
y++;
else if (r == 3 )
y--;
cout << "(" << x << ", " << y << ")" << endl;
}
x = (pow(x,2));
y = (pow(y,2));
int squaredDistance = x + y;
cout << "The squared distance is " << squaredDistance << endl;
}
Related
I developed a program to tabulate a given interval [a;b] with a step of c, and also find its largest and smallest value on this interval. I'm not sure if I have it right, so I wanted some advice. This code has a picture with a task condition.enter image description here
In the process of solving the given problem, apply the loop operator with a prerequisite. In the process of implementing the given task, assume that the argument of the function is identified as x, and the identifier of the variable responsible for the value of the function is y.
#include <iostream>
#include <math.h>
#include <clocale>
#define _USE_MATH_DEFINES
#include <iomanip>
#include<climits>
using namespace std;
int main(){
setlocale(LC_CTYPE, "");
double x, y, a, b, c;
double max, min, max_y, min_y;
max = -INT_MAX;
min = INT_MAX;
cout << "\n a:";
cin >> a;
cout << "\n b:";
cin >> b;
cout << "\n c:";
cin >> c;
cout << "\n a = " << a;
cout << " b = " << b;
cout << " c = " << c;
y = a;
while(y <= b){
if(y > 1) x = sin(sqrt(y + log(y)));
if((0 <= y) && (y <= 1)) x = M_PI + pow(cos(y + 1.2), 2);
if(y < 0) x = y * log10(pow(y,2) +2) + M_PI;
if(x > max){
max = x;
max_y = y;
}
if(x < min){
min = x;
min_y = y;
}
cout << "\n x = " << setw(8) << x << " y = " << setw(8) << y;
y += c;
}
cout << "\n The largest value in the given interval is" << max << " at y = " << max_y << "\n";
cout << "\n The smallest value in the given interval is" << min << " at y = " << min_y << "\n";
return 0;
}
When entering the values a,b,c into the console, our program should tabulate the function (output to the console) and find the smallest and largest value in the interval. I have the program working, but I'm not sure if it's correct. I would like to hear some advice
Added small updates:
Looks good overal
#include <iostream>
#include <cmath> //math.h == cmath
#include <clocale>
#define _USE_MATH_DEFINES
#include <iomanip>
#include<climits>
using namespace std;
void tabulate(double from, double to, double step)
{
double max, min, max_y, min_y, x = 0;
max = from; //they all start at 'from' anyway, its always best to set the max and min to first element of the array you're going through. They get overwritten anyway.
min = from;
for(double y = from; y < to; y += step)
{
if(y > 1) x = sin(sqrt(y + log(y)));
if((0 <= y) && (y <= 1)) x = M_PI + pow(cos(y + 1.2), 2);
if(y < 0) x = y * log10(pow(y,2) +2) + M_PI;
if(x > max){
max = x;
max_y = y;
}
if(x < min){
min = x;
min_y = y;
}
cout << " x = " << setw(8) << x << " y = " << setw(8) << y << endl;
}
cout << "The largest value in the given interval is " << max << " at y = " << max_y << endl;
cout << "The smallest value in the given interval is " << min << " at y = " << min_y << endl;
}
int main(){
setlocale(LC_CTYPE, "");
double a,b,c;
cout << "a: ";
cin >> a;
cout << "b: ";
cin >> b;
cout << "c: ";
cin >> c;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
tabulate(a,b,c);
return 0;
}
I am attempting to write a function that takes a value x and calculates the cos x by the series expansion, I'm always getting -inf, indifferent which value is read in.
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int fac(int n){
return n == 0 || n == 1 ? 1 : n * fac(n-1);
}
int main(){
double eps = 1e-15;
double x;
cin >> x;
long double ak = 1, sn = 0;
for(int k=1; abs(ak) > eps * abs(sn); k++){
double sgn = k % 2 == 0 ? 1 : -1;
sn += ak;
ak = sgn * pow(x, 2 * k) / fac(2*k);
}
cout << setprecision(4) << setw(5) << "x" << setprecision(15) << setw(20) << "cos x" << endl;
cout << setprecision(4) << setw(5)<< x << " " << setprecision(15) << setw(20) << sn << endl;
cout << setw(26) << cos(x) << endl;
return 0;
}
I debugged the code and at a certain point ak gets -inf. But why?
I can't seem to find what's wrong with my code, I'm trying to end the loop once the answers is equals to 0 but it keeps going on an infinite loop.
#include <iostream>
int main() {
using namespace std;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;
do{
while ( x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
while (x % 2 == 0)
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
}
while (x >= 0);
}
There are, essentially, two problems in your code, both of which, in themselves, will make your loop run endlessly.
Starting from the outside and working inwards: The test at the end of your (outer) while loop will always be "true", as you have while (x >= 0); so, even when x gets to zero (as it will), the loop will keep running! (And, once x is zero it will remain zero!)
Second, the two 'inner' while loops shouldn't be loops at all! You want one or the other 'block' to run once only for each main loop - so use an if ... else structure.
The following is a corrected version of your code:
#include <iostream>
int main() {
// using namespace std; // Generally, not good practice (and frowned-upon here on SO)
using std::cin; using std::cout; using std::endl; // Use only those you want to!
using std::string;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;
do {
if (x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
else // if (x % 2 == 0) ... but we don't need to test this again.
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}
There are a few other things that could be changed to make the code more "efficient," but I'll let you peruse the MNC (Minimum Necessary Change) before we start editing towards a BPC (Best Possible Code)!
EDIT: OK, due to 'peer pressure' from comments 😊, I'll put in a suggested BPC now:
#include <iostream>
int main() {
using std::cin; using std::cout; using std::endl; // Use only those you want to!
int x;// , remainder; // "remainder" is never used, so we can discard it!
cout << "Please enter a positive integer number: " << endl;
cin >> x; // Not critical, but I like to put such a cin right after the prompting cout.
std::string tab{ "\t" }; // Let's initialise more directly!
do {
// As there is only one line (now) inside each if/else block, we can leave out the {} ...
if (x % 2 != 0)
cout << x << " is odd" << tab << "Subtract 1" << tab << "Half of " << x - 1 << " is " << x / 2;
else
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
// We can put the following two line outside the tests, as they will be the same in both cases:
x = x / 2; // When x is ODD, this will give the SAME answer as x = (x - 1)/2 (as you noticed in your first cout)
cout << endl;
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}
Hellou guys, I am a beginner with self learner of C++.
today I tried to make a simple calculator but the debugger keeps on showing me the same error on and on. Unitianalized variable used "X" ; Unitianalized variable used "Z"
Here is the code :
#include <iostream>
using namespace std;
int main()
{
float x, z, a;
a = x + z;
cout << "Welcome to the calculator" << endl;
cout << "State the first number " << endl;
cin >> x ;
cout << "State the second number " << endl;
cin >> z ;
cout << "If you wanted to time number" << x << "by this number" << z << "The result would be : " << a << endl;
system("pause");
return 0;
}
You should initialize your variables and calculate a after you read x and z. Take a look at this: https://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/
#include <iostream>
using namespace std;
int main()
{
float x = 0.0f, z = 0.0f, a = 0.0f;
cout << "Welcome to the calculator" << endl;
cout << "State the first number " << endl;
cin >> x ;
cout << "State the second number " << endl;
cin >> z ;
a = x + z;
cout << "If you wanted to time number" << x << "by this number" << z << "The result would be : " << a << endl;
system("pause");
return 0;
}
The order in which you do things matters.
int x = 5, z = 2;
int a = x + z; // a is 7
z = 5; // a is still 7
a = x + z; // now a is updated to 10
So in your code when you do a = x + z; both x and z are uninitialized. It's undefined behavior to use uninitialized variables.
To fix it, move the a = x + z; to after you have input values to x and z.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i want to know how to turn this if else statement to a switch statement.this is a c++ program to out put the integers in the right order. i can't figure out a way.please help.thank you in advance.
int x, y, z;
cout << "please enter three integers:";
cin >> x >> y >> z;
if (x <= y && y <= z)
cout << x << " " << y << " " << z << endl;
else if (x <= z && z <= y)
cout << x << " " << z << " " << y << endl;
else if (y <= z && z <= x)
cout << y << " " << z << " " << x << endl;
else if (y <= x && x <= z)
cout << y << " " << x << " " << z << endl;
else if (z <= x && x <= y)
cout << z << " " << x << " " << y << endl;
else
cout << z << " " << y << " " << x << endl;
if (x <= y) {
if (z <= x) {
cout << z << " " << x << " " << y << endl;
} else {
if (z <= y) {
cout << x << " " << z << " " << y << endl;
} else {
cout << x << " " << y << " " << z << endl;
}
}
} else {
if (z >= x) {
cout << y << " " << x << " " << z << endl;
} else {
if (y >= z) {
cout << z << " " << y << " " << x << endl;
} else {
cout << y << " " << z << " " << x << endl;
}
}
}
That is not a good way to write a program. What if you need 4 integers?
One way to do it would be to use a list like std::vector and sort it.
vector<int> numbers;
int number = 0;
while (numbers.size() < 3 && cin >> number)
numbers.push_back(number);
sort(cbegin(numbers), cend(numbers)); // sorts ascending by default
for (auto number : numbers)
cout << number << " ";
cout << endl;
You can also use std::multiset which sorts its items automatically as they are inserted.
Instead of this approach, why don't you store the input in an array and try any of the sorting alogrithms to sort your input?
The answer in your particular case is you can't,
Your if statements have particular conditions, which,
wouldn't really work inside a switch.
An example of if/else if/else statements that can be
translated into a switch would be:
if(i == 1) {
// code here
} else if(i == 2) {
// code here
} else if(i == 3) {
// code here
} else {
// code here
}
which would translate to:
switch(i) {
case 1:
//code here
break;
case 2:
//code here
break;
case 3:
//code here
break;
default:
//code here
break;
}
Hope that helps a bit to understand a little more about switch statements.
If the challenge is that you can't sort the numbers, and the limit is 3 integers, then there are better ways to accomplish what you're doing.
#include <iostream>
using namespace std;
int main()
{
int combo[6][3] = {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}};
int values[3];
cin >> values[0] >> values[1] >> values[2];
for (int i = 0; i < 6; ++i )
{
if ( values[combo[i][0]] <= values[combo[i][1]] &&
values[combo[i][1]] <= values[combo[i][2]] )
{
cout << values[combo[i][0]] << " " << values[combo[i][1]] <<
" " << values[combo[i][2]];
break;
}
}
}
The combo array holds all of the combinations that can occur with 3 slots. Also note that the input is an array. Even if you didn't use the loop, the maximum if() statements you would need is 6.
However you should mention up front that this is a challenge, and what the restrictions are. Otherwise, please look at the other answers concerning storing and sorting these numbers.
You only need three conditional swaps to sort a list of three elements:
int x, y, z;
cout << "please enter three integers:";
cin >> x >> y >> z;
if (y < x) swap(y, x);
if (z < y) swap(z, y);
if (y < x) swap(y, x);
cout << x << " " << y << " " << z << endl;
Note that this approach doesn't scale. For 10 numbers, you would already need 45 conditional swaps.