Incorrect 'for' loop results C++ - c++

I am a beginner at using C++ so I was wondering if someone would be able to help me out as I'm currently trying to print a 'for' loop. The 'alfa' loop is printing correctly but when that information is called upon by the 'sina' loop, only zeros are being printed in the console.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <new>
#include <ctime>
#include <string>
#include <sstream>
#include <vector>
const double convToRad = pi/180.0;
int main(){
int INDEX = 91;
double alfa[INDEX] {0};
double sina[INDEX] {0};
for (int p = 90; p >= 0; p--){
alfa[INDEX] = p*convToRad;
//std::cout << alfa[INDEX] << std::endl;
}
for (int e = 0; e <= 90; e++){
sina[INDEX] = sin(alfa[INDEX]);
std::cout << sina[INDEX] << std::endl; //only prints 0's
}
return 0;
}

Your are accessing wrong memory location.
INDEX=91;
You had typed INDEX instead of p and e in both the loops.
So accessing a single wrong location which may gives a junk value or crash the program.

A few notes:
Don't use magical numbers, use constants.
Don't use the numbers in the array which are constant as you did.
Try a simple fix:
for (int p = 0; p < INDEX; p++) {
// storing 90* stuff in first index, 89* in second and so on...
alfa[p] = (90 - p) * convToRad;
// std::cout << alfa[p] << std::endl;
}
for (int e = 0; e < INDEX; e++) {
sina[e] = sin(alfa[e]);
std::cout << sina[e] << std::endl;
}

Related

Program not working for some reason, could someone pls help me fix it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Could someone please help me fix my program and explain why it s not working?
It's supposed to generate n points with 2 coordinates, which are both random numbers. The values themselves are random but have to scale the interval from 0 to some chosen value k. All the points have to be apart from each other by some radius which is taken to be 1.
For some reason my program doesn't even start. When I run it, Windows just says that the program is not responding and is trying to diagnose the problem.
Please simplify your explanation as much as possible since I'm a complete beginner and probably won't understand otherwise. Thanks a bunch in advance.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
int n=5;
int k=100;
vector<vector<double>> a(n, vector<double> (2));
srand(132);
//a[0][1]=k*((float(rand()))/RAND_MAX);
//a[0][0]=k*((float(rand()))/RAND_MAX);
for(int i=0; i<n;){
a[i][0]=k*((float(rand()))/RAND_MAX);
a[i][1]=k*((float(rand()))/RAND_MAX);
for (int j=0; j<n; j+=1){
if (sqrt(pow((a[i][1]-a[j][1]),2)+pow((a[i][0]-a[j][0]),2))<=1){
i=i;
break;}
else if(j==n-1){
cout << a[i][0] << " " << a[i][1] << endl;
i+=1;}
}}
return 0;
}
Your code lacks structure. That's why it is hard to understand, as you now learned even for you.
I think a good start would be to write a class for point and two functions, one for random points and for point distance then all, especially the double loops, will become much easier to read and debug.
Look at this:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct Point
{
Point() = default;
float x;
float y;
};
float scaled_random(int k)
{
return k*((float(rand()))/RAND_MAX);
}
float distance(const Point& a, const Point& b)
{
return sqrt(pow(a.y-b.y,2)+pow(a.x-b.x,2));
}
int main()
{
int n = 5;
int k = 100;
vector<Point> a(n);
srand(132);
for (int i=0; i<n; ) {
a[i].x = scaled_random(k);
a[i].y = scaled_random(k);
for (int j=0; j<n; j+=1) {
if (distance(a[i], a[j]) <= 1) {
i = i;
break;
} else if (j == n-1) {
cout << a[i].x << " " << a[i].y << endl;
i += 1;
}
}
}
return 0;
}
The issue is still the same, but it has now more structure, better formatting and superfluous includes removed.
Maybe you can see the problem yourself much better this way.
The first time through your code i and j will both be zero, this means a[i][1] - a[j][1] and a[i][0] - a[j][0] are zero, this resets i to 0, breaks the loop and starts again resulting in an infinite loop.
Checking i != j fixes the problem:
if (i != j && sqrt(pow((a[i][1] - a[j][1]), 2) + pow((a[i][0] - a[j][0]), 2)) <= 1) {
Your code might be better structured as:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <algorithm>
int main()
{
int n = 5;
int k = 100;
std::vector<std::vector<double>> a(n, std::vector<double>(2));
srand(132);
for (int i = 0; i < n; i++) {
auto end = a.begin() + i;
do
{
a[i][0] = k * ((float(rand())) / RAND_MAX);
a[i][1] = k * ((float(rand())) / RAND_MAX);
}
while (end != std::find_if(a.begin(), end, [&](const std::vector<double>& element)
{
return sqrt(pow((a[i][1] - element[1]), 2) + pow((a[i][0] - element[0]), 2)) <= 1;
}));
std::cout << a[i][0] << " " << a[i][1] << "\n";
}
return 0;
}
Using this code only the values before i are checked each time rather than all of the values.
rand should be avoided in modern c++, see Why is the use of rand() considered bad?
As the elements of your vector always have 2 elements it'd be better to use std::pair or std::array.
pow may be quite an inefficient way to square two numbers. The sqrt could be avoided by squaring your distance instead.
Using the above points your code could become:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <array>
#include <random>
using point = std::array<double, 2>;
double distanceSquared(const point& a, const point& b)
{
auto d0 = a[0] - b[0];
auto d1 = a[1] - b[1];
return d0 * d0 + d1 * d1;
}
int main()
{
int n = 5;
int k = 100;
std::vector<point> a(n);
std::random_device rd;
std::mt19937_64 engine(rd());
std::uniform_real_distribution<double> dist(0, k);
for (int i = 0; i < n; i++) {
auto end = a.begin() + i;
do
{
a[i][0] = dist(engine);
a[i][1] = dist(engine);
}
while (end != std::find_if(a.begin(), end, [&](const point& element)
{
return distanceSquared(a[i], element) <= 1;
}));
std::cout << a[i][0] << " " << a[i][1] << "\n";
}
return 0;
}

Unable to understand the output in C++ Pointers. (Working with loops in pointers)

Unable to understand the unexpected output. The pointer doesn't point to the 0th index no. of a string
I have been trying to find the reason for the output of the following program. the loop starts from i=0 but there is no character being displayed at the 0th index no. and the loop starts from the 1st index no.
#include <conio.h>
#include <iostream.h>
#include <string.h>
int main()
{
clrscr();
int i, n;
char *x = "Alice";
n = strlen(x);
*x = x[n];
for (i = 0; i <= n; i++)
{
cout << x;
x++;
}
cout << endl << x;
getch();
}
I am getting the following output: liceicecee
But I expected the output to start from 'A'.
You should really upgrade to a modern compiler. There are many free ones available.
#include <iostream.h> // non-standard header file
#include <string.h> // not recommended - it brings its functions into the global namespace
void main() { // main must return "int"
int i, n;
char* x = "Alice"; // illegal, must be const char*
n = strlen(x);
*x = x[n]; // illegal copy of the terminating \0 to the first const char
for(i = 0; i <= n; i++) { // <= includes the terminating \0
cout << x; // will print: "", "lice", "ice", "ce", "e", ""
// since you move x forward below
x++;
}
cout << endl << x; // x is now pointing after the \0, undefined behaviour
}
If you want to print the letters one by one (using your current program as a base) using standard C++:
#include <iostream>
#include <cstring>
int main() {
const char* x = "Alice";
size_t n = std::strlen(x);
for(size_t i = 0; i < n; ++i, ++x) {
std::cout << *x; // *x to dereferece x to get the char it's pointing at
}
std::cout << "\n"; // std::endl is overkill, no need to flush
}
What strlen does is to search for the first \0 character and to count how long it had to search. You really don't need to do that here since you are going through all the characters (by stepping x) yourself. Illustration:
#include <iostream>
int main() {
const char* x = "Alice";
size_t n = 0;
while(*x != '\0') {
std::cout << *x;
++x;
++n;
}
std::cout << "\nThe string was " << n << " characters long\n";
}

C++ Unexpectedly Exiting For Loop

I am working through Andrew Koenig's Accelerated C++, and one of the exercises asks to write a program to output two columns, one of integers up to some maxInt and the other of their squares. Here is my code:
#include <iostream>
#include <iomanip>
#include <string>
using std::cout;
using std::endl;
using std::setw;
using std::to_string;
using std::string;
int square(const int n)
{
return n*n;
}
int main()
{
// loop until maxInt
const int maxInt = 1000;
// use the length of maxInt and its square to comptue width later on
const int maxIntSize = to_string(maxInt).length();
const int maxIntSquareSize = to_string(square(maxInt)).length();
for (int i = 1; i != maxInt + 1; ++i) {
const int j = square(i);
// we need iSize to compute the width
const int iSize = to_string(i).length();
const int width = maxIntSize + maxIntSquareSize + 1 - iSize;
cout << i << setw(width) << j << endl;
}
return 0;
}
My problem is that the program is inconsistent. Sometimes it works as I expect, other times it stops printing prematurely. Furthermore, when it doesn't do what I expect, the behavior is rather unpredictable. Could anyone let me know what I'm doing wrong?
(Also, I am new to C++, so any general advice is appreciated.)

Trying to print the contents of a vector to a text file using visual C++

I'm trying to get used to using vectors to store information and I need to write the contents of a vector to a file. My code stores the pixel information from inside a box with a variable width and height. I'm trying to test out printing the vector by putting the number 255 in each position of the vector. When I run my code and create the file, I only have 0's. Is there something I'm missing? Here is my code:
#include <iostream>
#include <string>
#include <math.h>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <strstream>
#include<vector>
using namespace std;
vector<int> ROIPixels;
G_BoxWidth = 250;
G_BoxHeight = 100;
int TopBox = G_BoxY;
int LeftBox = G_BoxX;
int RightBox = G_BoxX + G_BoxWidth - 1;
int BottomBox = G_BoxY + G_BoxHeight - 1;
int vColMax = G_BoxWidth;
int vLineMax = G_BoxHeight;
ROIPixels.clear();
ROIPixels.resize(vColMax*vLineMax*4, 0); //I'm multiplying by 4 because
//i'm using a bitmap
iCol = LeftBox;
while (iCol <= RightBox)
{
iLine = TopBox;
while (iLine <= BottomBox)
{
ROIPixels.push_back(255);
iLine++;
}
iCol++;
}
if (CaptureImage_Flag == 2)
{
//## Save arrImage1 to file "arrImage2.dat"
string OutFileName = "ROIPixels.dat";
ofstream OutFile(OutFileName.c_str(), ios::out);
if (!OutFile)
{
cerr << "Error: " << OutFileName << "could not be created."
<< std::endl;
exit(1);
}
for (unsigned int ii = 0; ii < vColMax*vLineMax * 4; ii++)
{
if (ii / 4. == (int)(ii / 4.))
{
OutFile << (int)(ROIPixels[ii]) << endl;
}
}
OutFile.close();
exit(1);
}
I would greatly appreciate any help or suggestions for my code. Thank you.
Your call to resize() puts vColMax*vLineMax*4 zeros in your vector.
Then push_back adds a bunch of 255 values, without replacing or removing the zeros.
Finally, you print out the first vColMax*vLineMax*4 items, which are the zeros from resize().

merging a collection of `Eigen::VectorXd`s into one large `Eigen::VectorXd`

If you go to this Eigen page, you'll see you can initialize VectorXd objects with the << operator. You can also dump a few vector objects into one big VectorXd object (e.g. look at the third example in the section called "The comma initializer").
I want to dump a few vectors into a big vector, but I'm having a hard time writing code that will work for an arbitrarily sized collection of vectors. The following doesn't work, and I'm having a hard time writing it in a way that does (that isn't a double for loop). Any suggestions?
#include <iostream>
#include <Eigen/Dense>
#include <vector>
int main(int argc, char **argv)
{
// make some random VectorXds
std::vector<Eigen::VectorXd> vOfV;
Eigen::VectorXd first(3);
Eigen::VectorXd second(4);
first << 1,2,3;
second << 4,5,6,7;
vOfV.push_back(first);
vOfV.push_back(second);
// here is the problem
Eigen::VectorXd flattened(7);
for(int i = 0; i < vOfV.size(); ++i)
flattened << vOfV[i];
//shows that this doesn't work
for(int i = 0; i < 7; ++i)
std::cout << flattened(i) << "\n";
return 0;
}
The comma initializer does not work like that. You have to fully initialize the matrix from that. Instead, allocate a large enough vector and iterate and assign the blocks.
#include <iostream>
#include <vector>
#include <Eigen/Dense>
// http://eigen.tuxfamily.org/dox/group__TopicStlContainers.html
#include <Eigen/StdVector>
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::VectorXd)
int main()
{
// make some random VectorXds
std::vector<Eigen::VectorXd> vOfV;
Eigen::VectorXd first(3);
Eigen::VectorXd second(4);
first << 1,2,3;
second << 4,5,6,7;
vOfV.push_back(first);
vOfV.push_back(second);
int len = 0;
for (auto const &v : vOfV)
len += v.size();
Eigen::VectorXd flattened(len);
int offset = 0;
for (auto const &v : vOfV)
{
flattened.middleRows(offset,v.size()) = v;
offset += v.size();
}
std::cout << flattened << "\n";
}