New at c++ so if I get any terms wrong please don't ridicule me. I am trying to write a program that will draw ask the user for units and then draw house using functions. The problem that I am having is in my drawcone function Here is my progress so far.
#include<iostream>
using namespace std;
void drawcone(int height);
void drawHorizontalLine(int numXs);
void draw2VerticalLines(int numSpaces, int numRows);
void drawOneRow(int numSpaces);
void getDimensions(int& width, int& height);
void drawbox(int width, int height);
int main(){
int width;
int height;
getDimensions(height, width);
drawcone(height);
drawHorizontalLine(width);
draw2VerticalLines(width - 2, height - 2);
drawHorizontalLine(width);
return 0;
}
void drawbox(int width, int height){
drawHorizontalLine(width);
draw2VerticalLines(width - 2, height - 2);
drawHorizontalLine(width);
}
void drawcone(int height){
int base = height * 2;
int r = 0;
while ( r != height){
int c = 0;
while (c != base){
if(c==height-r || c==height+r)
cout << "X";
else
cout << " ";
c++;
}
cout << endl;
r++;
}
}
void drawHorizontalLine(int numXs)
{
int count;
for (count = 0; count < numXs; count++){
cout << "X";
}
cout << endl;
}
void draw2VerticalLines(int numSpaces, int numRows)
{
int rowCount;
for (rowCount = 0; rowCount < numRows; rowCount++){
drawOneRow(numSpaces);
}
}
void drawOneRow(int numSpaces)
{
int spaceCount;
cout << "X";
for (spaceCount = 0; spaceCount < numSpaces; spaceCount++){
cout << " ";
}
cout << "X" << endl;
}
void getDimensions(int& width, int& height){
cout << "Enter the width of the house" << endl;
cin >> width;
cout << "Enter the height of the house" << endl;
cin >> height;
}
The correct sample output would look like this
X
X X
X X
XXXXX
X X
X X
XXXXX
My current output looks like this
X
X X
X X
X X
XXXX
X X
X X
XXXX
I would like the cone to be slightly smaller so it will be proportionate to the box. I would also prefer an answer that does not involve modifying the drawbox function. Thank you for your time!
Here's one solution. However, the cone will be symmetrical only if the width is odd.
#include<iostream>
using namespace std;
void drawcone(int height);
void drawHorizontalLine(int numXs);
void draw2VerticalLines(int numSpaces, int numRows);
void drawOneRow(int numSpaces);
void getDimensions(int& width, int& height);
void drawbox(int width, int height);
int main() {
int width;
int height;
getDimensions(width, height);
drawcone(width);
drawHorizontalLine(width);
draw2VerticalLines(width - 2, height - 2);
drawHorizontalLine(width);
return 0;
}
void drawbox(int width, int height) {
drawHorizontalLine(width);
draw2VerticalLines(width - 2, height - 2);
drawHorizontalLine(width);
}
void drawcone(int width) {
for (int i=0; i<(width/2 + width%2); i++) {
for (int j=width/2-i; j>0; j--) {
cout << " ";
}
drawOneRow(i*2-1);
}
}
void drawHorizontalLine(int numXs)
{
int count;
for (count = 0; count < numXs; count++) {
cout << "X";
}
cout << endl;
}
void draw2VerticalLines(int numSpaces, int numRows)
{
int rowCount;
for (rowCount = 0; rowCount < numRows; rowCount++) {
drawOneRow(numSpaces);
}
}
void drawOneRow(int numSpaces)
{
int spaceCount;
cout << "X";
if (numSpaces > 0) {
for (spaceCount = 0; spaceCount < numSpaces; spaceCount++) {
cout << " ";
}
cout << "X";
}
cout << endl;
}
void getDimensions(int& width, int& height) {
cout << "Enter the width of the house" << endl;
cin >> width;
cout << "Enter the height of the house" << endl;
cin >> height;
}
Should be fairly easy to debug, it's printing out the wrong number of spaces for the 'roof' of the house.
The problem should be contained in the while ( r != height) block
try messing with the else {cout << " ";} with else if(c%2==1){cout << " ";}
#include<iostream>
using namespace std;
void roof(int height);
void hLine(int num);
void vLine(int spaces, int rows);
void row(int spaces);
void dimensions(int& width, int& height);
void box(int width, int height);
int main()
{
int width;
int height;
dimensions(height, width);
roof(height);
hLine(width);
vLine(width - 2, height - 2);
hLine(width);
return 0;
}
void box(int width, int height)
{
hLine(width);
vLine(width - 2, height - 2);
hLine(width);
}
void roof(int height)
{
int base = height * 2;
int r = 0;
while ( r != height)
{
int c = 0;
while (c != base)
{
if(c==height-r || c==height+r)
cout << "*";
else
cout << " ";
c++;
}
cout << endl;
r++;
}
}
void hLine(int num)
{
int count;
for (count = 0; count < num*2+1; count++)
{
cout << "-";
}
cout << endl;
}
void vLine(int spaces, int rows)
{
int numrows;
for (numrows = 0; numrows < rows; numrows++)
{
row(spaces);
}
}
void row(int spaces)
{
int numspaces;
cout << "{";
for (numspaces = 0; numspaces < spaces*2+3; numspaces++)
{
cout << "$";
}
cout << "}" << endl;
}
void dimensions(int& width, int& height)
{
cout<<"Enter the width of the house"<<endl;
cin>>width;
cout<<"Enter the height of the house"<<endl;
cin>>height;
}
Related
I know there are so many libraries in this code. That's because I was trying everything and also testing some other things. The problem is that function called "wspak" is not outputted well in my main function. I mean, for example, it outputs the first or last index 10 times instead of outputting all 10 indexes once. I hope you all will understand this code, because I use polish appellations for my variables. This is my code so far:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
#include <time.h>
#include <stdio.h>
#include <conio.h>
#include <random>
#include <stdlib.h>
#include <algorithm>
using namespace std;
float maxitab(int n, float tab[]); //deklaracja funkcji
float minitab(int n, float tab[]); //deklaracja funkcji
float wspak(int n, float tab[]); //deklaracja funkcji
double rand_double()
{
return ((double)rand()) / ((double)RAND_MAX);
}
double rand_double_interval(double a, double b)
{
return rand_double() * (b - a) + a;
}
int main(int argc, char* argv[])
{
srand(time(NULL));
int n;
float* tab;
cout << "Program wyszuka najwiekszy element tablicy.\n";
cout << "Podaj ilosc elementow tablicy: ";
cin >> n;
tab = new float[n];
for (int i = 0; i < n; i++)
{
float wylosowane_liczby = rand_double_interval(-1, 1);
tab[i] = wylosowane_liczby;
}
cout << "WYLOSOWANE z przedzialu <-1,1> elementy tablicy to: " << endl;
for (int i = 0; i < n; i++)
{
cout << tab[i] << endl;
}
cout << "\nNajwiekszy WYLOSOWANY z przedzialu <-1,1> element tablicy to: " << maxitab(n, tab);
cout << "\nNajmniejszy WYLOSOWANY z przedzialu <-1,1> element tablicy to: " << minitab(n, tab);
cout << "\nTablica od konca do poczatku: " << endl;
for (int i = 0; i < n; i++)
{
cout << wspak(n, tab);
}
delete[] tab;
cout << endl;
cout << endl;
cout << endl;
return 0;
}
float maxitab(int n, float tab[]) //definicja funkcji
{
float maximum = tab[0];
for (int i = 1; i < n; i++)
{
if (tab[i] > maximum)
{
maximum = tab[i];
}
}
return maximum;
}
float minitab(int n, float tab[]) //definicja funkcji
{
float minimum = tab[0];
for (int i = 1; i < n; i++)
{
if (tab[i] <= minimum)
{
minimum = tab[i];
}
}
return minimum;
}
float wspak(int n, float tab[]) //definicja funkcji
{
float wspak = 0;
for (int i = n - 1; i >= 0; i--)
{
if (tab[i] < wspak)
{
wspak = tab[i];
}
}
return wspak;
}
float wspak(int n, float tab[]); //deklaracja funkcji
wspak(n, tab);
void wspak(int n, float tab[]) //definicja funkcji
{
for (int i = n - 1; i >= 0; i--)
{
cout << tab[i] << ' ' << endl;
}
cout << '\n';
}
I'm attempting to interact with a 2D array thorough the Board class. However, I'm getting a segmentation fault when running the main file containing this code:
#include "Board.h"
int main(int argc, char** argv)
{
int height = 0;
int width = 0;
int pop_density = 0.8;
Board* c = new Board(height,width);
c->print();
c->populate(pop_density);
c->print();
//for (i )
cout << c->read_char_at_index(1,2) << endl;
delete c;
return 0;
}
This is the Board.cpp Code:
#include "Board.h"
//in board: make a fucntion that pulls from file
Board::Board(int h, int w)
{
m_height = h;
m_width = w;
m_array = new char* [m_height];
for (int i = 0; i < m_height; ++i)
{
m_array[i] = new char[m_width];
for (int j = 0; j < m_width; ++j)
{
m_array[i][j] = '-';
}
}
cout << "Made board" << endl;
}
Board::~Board()
{
for (int i = 0; i < this->m_height; ++i)
{
delete[] this->m_array[i];
}
delete[] this->m_array;
cout << "Destructed Board" << endl;
}
void Board::print()
{
for (int i = 0; i < this->m_height; ++i)
{
for (int j = 0; j < this->m_width; ++j)
{
cout << this->m_array[i][j] << " ";
}
cout << endl;
}
}
void Board:: populate(double density)
{
//seeding rand with time
srand(time(NULL));
int totalCells = this->m_height * this->m_width;
int cellsToFill = round(totalCells * density);
int cellsFilled = 0;
for (int i = 0; i < cellsToFill; ++i)
{
int randomRow = rand() % this->m_height;
int randomColumn = rand() % this->m_width;
this->m_array[randomRow][randomColumn] = 'X';
}
}
void Board:: write_char_at_index(int height, int width, char z)
{
cout << "pre" << endl;
cout << height << " " << width << endl;
m_array[height][width] = z;
cout << "Wrote" << endl;
}
char Board:: read_char_at_index(int height, int width)
{
return m_array[height][width];
cout << "read" << endl;
}
And the Board.h Code:
#ifndef BOARD_H
#define BOARD_H
#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
//This class is used to make a Board object
class Board
{
public:
Board(int h, int w);
~Board();
void print(); // Prints the board to cout
void populate(double density); // Populates board based on density input
void write_char_at_index(int height, int width, char z);
char read_char_at_index(int height, int width);
private:
char** m_array; // 2D array dynamically allocated during runtime
int m_height;
int m_width;
};
#endif
Any help or advice would be great, as I've already asked two classmates and they're not sure what the problem is. I know for sure the index I'm trying to assign the char value to is not out of bounds.
The input parameters of read_char_at_index are (1,2) in the main function. However, The Board object c is with height = 0 and width = 0. You can modify the value of height and width to large enough values, such as 10, 10.
int height = 10;
int width = 10;
int pop_density = 0.8;
Board* c = new Board(height, width);
c->print();
c->populate(pop_density);
c->print();
cout << c->read_char_at_index(1, 2) << endl;
The program may run without Segmentation Fault.
Note: The functions "write_char_at_index" and "read_char_at_index" may check the input values (height and width) to ensure the access to m_array member is safe.
if (height >= this->m_height || width >= this->m_width)
{
return;
}
Pointers are still a little confusing to me. I want the split function to copy negative elements of an array into a new array, and positive elements to be copied into another new array. A different function prints the variables. I've included that function but I don't think it is the problem. When the arrays are printed, all elements are 0:
Enter number of elements: 5
Enter list:1 -1 2 -2 3
Negative elements:
0 0
Non-Negative elements:
0 0 0
I assume that the problem is that in the split function below i need to pass the parameters differently. I've tried using '*' and '**' (no quotes) for passing the parameters but I get error messages, I may have done so incorrectly.
void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
int a = 0;
int b = 0;
for (int i = 0; i < aSize; ++i) {
if (alpha[i] < 0) {
alpha[i] = bravo[a];
++a;
}
else {
alpha[i] = charlie[b];
++b;
}
}
if (a + b != aSize) {
cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
exit(0);
}
}
my main function (all arrays are required to be pointers):
int num_elements;
cin >> num_elements;
int * arr1 = new int[num_elements];
int x;
cout << "Enter list:";
for (int i = 0; i < num_elements; ++i) {
cin >> x;
arr1[i] = x;
}
int y = 0;
int z = 0;
count(arr1, num_elements, y, z);
int * negs = new int [y];
int * nonNegs = new int[z];
split(arr1, negs, nonNegs, num_elements, y, z);
cout << "Negative elements:" << endl;
print_array(negs, y);
cout << endl;
cout << "Non-Negative elements:" << endl;
print_array(nonNegs, z);
cout << endl;
All functions:
void count(int A[], int size, int & negatives, int & nonNegatives) {
for (int i = 0; i < size; ++i) {
if (A[i] < 0) {
++negatives;
}
if (A[i] >= 0) {
++nonNegatives;
}
}
}
void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
int a = 0;
int b = 0;
for (int i = 0; i < aSize; ++i) {
if (alpha[i] < 0) {
alpha[i] = bravo[a];
++a;
}
else {
alpha[i] = charlie[b];
++b;
}
}
if (a + b != aSize) {
cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
exit(0);
}
}
void print_array(int A[], int size) {
for (int i = 0; i < size; ++i) {
cout << A[i] << " ";
}
}
All help is appreciated.
EDIT: I apologize for my unclear question, I was wondering how to get my arrays to behave as I want them to.
Array is behaving correctly as per instruction :), you are doing minor mistake (may be overlook) in split function. I have commented out the statement and given reason of problem, please correct those two line of code, rest is fine.
void split(int alpha[], int bravo[], int charlie[], int aSize, int bSize, int cSize) {
int a = 0;
int b = 0;
for (int i = 0; i < aSize; ++i) {
if (alpha[i] < 0) {
//alpha[i] = bravo[a];// here alpha is your source array, don't overwrite it
bravo[a] = alpha[i];
++a;
}
else {
//alpha[i] = charlie[b];// here alpha is your source array, don't overwrite it
charlie[b] = alpha[i];
++b;
}
}
if (a + b != aSize) {
cout << "SOMETHING HAS GONE HORRIBLY WRONG!";
exit(0);
}
}
(Edit: change suggested in the comments section now allows the desired behavior)
I'm developing an agent-based simulation in C++, and so far I'm able to run 1 simulation and I transcribe the results manually. It consists of an Environment class with a 2-d array with agents (hunters and preys)
To automate the data collection, I'm trying to implement some functions so that I can later transcribe relevant results of each simulation to a CSV file.
The following code in Visual Studio generates the Environment, populates it, counts the agents and display an ASCI map of the hunters and preys with a legend.
#include <iostream>
#include <cstdlib> // for rand
#include <ctime> // for time
#include <vector>
#include <Windows.h> //for color in output
using namespace std;
const int WORLDSIZEX = 100;
const int WORLDSIZEY = 30;
enum AgentType { PREY, HUNTER };
class Environment;
class Agent {
public:
Agent(Environment* aWorld, int xcoord, int ycoord);
virtual ~Agent() { }
virtual AgentType getType() const = 0;
virtual char representation() const = 0;
protected:
int x;
int y;
Environment* world;
private:
};
struct Position {
int x;
int y;
};
class Environment {
public:
Environment(unsigned int seed, int _id, int _initialPopulationPreys, int _initialPopulationHunmters);
~Environment();
Agent* getAt(int x, int y) const;
void setAt(int x, int y, Agent* org);
void display();
Position randomPosition() const;
Position randomPositionHunter() const;
int numberPreys();
int numberHunters();
private:
Agent* grid[WORLDSIZEX][WORLDSIZEY];
void createOrganisms(AgentType orgType, int count);
int id;
int timeStep;
int initialPopulationPreys;
int initialPopulationHunters;
};
class Hunter : public Agent {
public:
Hunter(Environment* aWorld, int xcoord, int ycoord);
AgentType getType() const;
char representation() const;
private:
bool altruistic;
};
class Prey : public Agent {
public:
Prey(Environment* aWorld, int xcoord, int ycoord);
AgentType getType() const;
char representation() const;
private:
int huntingDifficulty;
};
Prey::Prey(Environment* aWorld, int xcoord, int ycoord) : Agent(aWorld, xcoord, ycoord) { huntingDifficulty = int(rand() % 3); }
AgentType Prey::getType() const { return PREY; }
char Prey::representation() const { return 'o'; }
Hunter::Hunter(Environment* aWorld, int xcoord, int ycoord) : Agent(aWorld, xcoord, ycoord) { }
AgentType Hunter::getType() const { return HUNTER; }
char Hunter::representation()const { return 'X'; }
Agent::Agent(Environment* aWorld, int xcoord, int ycoord) {
world = aWorld;
x = xcoord;
y = ycoord;
world->setAt(x, y, this);
}
Environment::Environment(unsigned int seed, int _id, int _initialPopulationPreys, int _initialPopulationHunters) {
srand(seed);
id = _id;
initialPopulationPreys = _initialPopulationPreys;
initialPopulationHunters = _initialPopulationHunters;
for (int i = 0; i < WORLDSIZEX; i++) {
for (int j = 0; j < WORLDSIZEY; j++) {
grid[i][j] = NULL;
}
}
timeStep = 0;
createOrganisms(PREY, initialPopulationPreys);
createOrganisms(HUNTER, initialPopulationHunters);
}
Environment::~Environment() {
for (int i = 0; i < WORLDSIZEX; i++) {
for (int j = 0; j < WORLDSIZEY; j++) {
if (grid[i][j] != NULL) {
delete grid[i][j];
}
}
}
}
Agent* Environment::getAt(int x, int y) const {
if ((x >= 0) && (x < WORLDSIZEX) && (y >= 0) && (y < WORLDSIZEY)) {
return grid[x][y];
}
else {
return NULL;
}
}
void Environment::setAt(int x, int y, Agent* org) {
if ((x >= 0) && (x < WORLDSIZEX) && (y >= 0) && (y < WORLDSIZEY)) {
grid[x][y] = org;
}
}
// Displays the world in ASCII.
void Environment::display() {
int numPreys = 0;
int numHunters = 0;
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
// Remember how things were when we started
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hstdout, &csbi);
cout << endl << endl;
for (int j = 0; j < WORLDSIZEY; j++) {
for (int i = 0; i < WORLDSIZEX; i++) {
if (grid[i][j] == NULL) {
cout << "_";
}
else {
if (grid[i][j]->getType() == PREY) {
SetConsoleTextAttribute(hstdout, 10);
numPreys++;
}
else if (grid[i][j]->getType() == HUNTER) {
SetConsoleTextAttribute(hstdout, 12);
numHunters++;
}
cout << grid[i][j]->representation();
SetConsoleTextAttribute(hstdout, csbi.wAttributes);
}
}
cout << endl;
}
cout << "Preys 'o': " << numPreys << " Hunters 'X': " << numHunters << endl;
cout << "Timestep:" << timeStep << " World ID:" << id << endl;
}
Position Environment::randomPosition() const { // returns a random number in the range 0 to WORLDSIZEX - 1 (or WORLDSIZEY - 1)
Position p;
p.x = rand() % WORLDSIZEX;
p.y = rand() % WORLDSIZEY;
return p;
}
Position Environment::randomPositionHunter() const { // returns a random number in the central fifth of the grid
Position p;
int subGridSizeX = WORLDSIZEX / 5;
int subGridSizeY = WORLDSIZEY / 5;
p.x = subGridSizeX * 1 + (rand() % (3 * subGridSizeX));
p.y = subGridSizeY * 2 + (rand() % subGridSizeY);
return p;
}
int Environment::numberPreys() {
int numPreys = 0;
for (int j = 0; j < WORLDSIZEY; j++) {
for (int i = 0; i < WORLDSIZEX; i++) {
if (grid[i][j] && grid[i][j]->getType() == PREY) {
numPreys++;
}
}
}
return numPreys;
}
int Environment::numberHunters() {
int numHunters = 0;
for (int j = 0; j < WORLDSIZEY; j++) {
for (int i = 0; i < WORLDSIZEX; i++) {
if (grid[i][j] && grid[i][j]->getType() == HUNTER) {
numHunters++;
}
}
}
return numHunters;
}
void Environment::createOrganisms(AgentType orgType, int count) {
int orgCount = 0;
while (orgCount < count) {
Position p = randomPosition();
Position q = randomPositionHunter();
if (orgType == PREY) {
if (grid[p.x][p.y] == NULL) { // Only put Organism in empty spot
orgCount++;
new Prey(this, p.x, p.y); // Create a Prey and put it into the world
}
}
else if (orgType == HUNTER) {
if (grid[q.x][q.y] == NULL) { // Only put Organism in empty spot
orgCount++;
new Hunter(this, q.x, q.y); // Create a Hunter and put it into the world
}
}
}
}
int main() {
int initialPreys = 60;
int initialHunters = 15;
int id = 0;
//Creating the environment
int seed = time(0);
Environment myWorld(seed, id, initialPreys, initialHunters);
cout << "This is the setup of the environment for all the simulations" << endl;
myWorld.display();
char ch;
return 0;
}
I would like to replace the Environment::display() function with:
void Environment::display() {
int numPreys = numberPreys();
int numHunters = numberHunters();
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
// Remember how things were when we started
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hstdout, &csbi);
cout << endl << endl;
for (int j = 0; j < WORLDSIZEY; j++) {
for (int i = 0; i < WORLDSIZEX; i++) {
if (grid[i][j] == NULL) {
cout << "_";
}
else {
if (grid[i][j]->getType() == PREY) {
SetConsoleTextAttribute(hstdout, 10);
}
else if (grid[i][j]->getType() == HUNTER) {
SetConsoleTextAttribute(hstdout, 12);
}
cout << grid[i][j]->representation();
SetConsoleTextAttribute(hstdout, csbi.wAttributes);
}
}
cout << endl;
}
cout << "Preys 'o': " << numPreys << " Hunters 'X': " << numHunters << endl;
cout << "Timestep:" << timeStep << " World ID:" << id << endl;
}
But then, the function doesn't display anything and the console window closes after a while.
My question: How can I call the counting functions inside of the display function?
I have a program I'm making to calculate the area of a rectangle using measurements specified by the user. I'm using a class to do this for specific reasons, but my compiler generates two errors...
expression must have class type
left of '.getArea' must have class/struct/union
How do I fix this?
Rectangle.h
class Rectangle
{
private:
int length;
int width;
int area = length * width;
public:
Rectangle(int l, int w);
int getLength();
void setLength(int l);
int getWidth();
void setWidth(int w);
int getArea();
void setArea(int a);
};
Rectangle.cpp
Rectangle::Rectangle(int l, int w)
{
length = l;
width = w;
}
--some code--
int Rectangle::getArea()
{
return area;
}
void Rectangle::setArea(int a)
{
area = a;
}
Area.cpp
int i, lth, wth;
for (i = 0; i < 3; i++)
{
cout << "Enter your measurements, length first" << endl;
cin >> lth >> wth;
Rectangle rMeasure(int lth, int wth);
cout << "Area of this rectangle is: " << rMeasure.getArea(); //problem code
}
This
Rectangle rMeasure(int lth, int wth);
is a function declaration.
It seems you mean
Rectangle rMeasure(lth, wth);
Few changes in your code is required
1.
private:
int length;
int width;
int area;
2.
Rectangle::Rectangle(int l, int w)
{
length = l;
width = w;
this->area=length * width;
}
3.
for (i = 0; i < 3; i++)
{
cout << "Enter your measurements, length first" << endl;
cin >> lth >> wth;
Rectangle rMeasure(lth, wth);
cout << "Area of this rectangle is: " << rMeasure.getArea();
}
Demo