• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Well the Microsoft surface pro as well as an Asus tablet ( the model name escapes me at the moment ) would both have the ability to do what you're looking for. Note that the regular Microsoft surface as well as the Asus vivotab RT won't be suited for such a purpose considering I believe that software support as it relates to development tools for windows rt is basically nonexistent at the moment. The pro and the other tablet run windows 8, so as far as I know you can install anything on those that you could on a desktop using windows 8.

If you're looking for something Linux based, there are rumours of an Ubuntu tablet coming out this year, or at the very least a customized version of Ubuntu meant for tablets (the company that makes Ubuntu has stated as much).

That's about all I know at the moment. Note that the surface pro is fairly expensive. If you always have a reliable Internet connection, windows 8 has fairly good remote desktop support so if you have a machine at home running windows 8 and and a windows rt tablet you could attempt to program via remote desktop. My friend was having an issue doing this the other day though as some scroll bars in visual studio weren't able to be moved via touch. For some reason it kept trying to move the entire visual studio screen instead of just scrolling the page of code. For that reason I wouldn't suggest this route but I suppose it could be worth a try.
 

mackattk

Member
So I am taking the second C++ class, and I have run into a little snag. I need to do everything by functions. I have the program working. It is a pretty simple program, and basically what it is is that the user inputs the amount of rainfall each month. The info is stored in an array and passed to and from the functions. I got that working, the only problem I am having is that I do not know how to assign a month array to the rainfall array, and having it pass through all the functions.

I copied the code below.

I am not sure why I am strugging with programming. I guess I need to learn a programming mindset and put some more time into it. I can usually pick up computer related tasks relatively fast, but this tougher than usual for me.

Code:
#include <iostream>
#include <iomanip>
using namespace std;

void getMonths(double[], int);
double getAverage(const double[], int);
double getLowest(const double[], int);
double getHighest(const double[], int);
void rainOutput(const double [], double, double, double);

int main()
{
	const int Num_Months = 12;
	double rainFall[Num_Months],
		average,
		lowestfall,
		highestfall;


	getMonths(rainFall, Num_Months);
	average=getAverage(rainFall, Num_Months);
	lowestfall=getLowest(rainFall, Num_Months);
	highestfall=getHighest(rainFall, Num_Months);
	rainOutput(rainFall, average, lowestfall, highestfall);
	return 0;
	system("PAUSE");
}

void getMonths(double rainFall[], int Num_Months)
{
	int index;
	for(index = 0; index <=Num_Months -1; index++)
	{
		cout << "Enter rainfall for month #"
			<< (index + 1) << ": ";
			cin >> rainFall[index];
			while (rainFall[index] < 0)
			{
				cout << "Please enter a positive amount of rain" << endl;
				cin >> rainFall[index];
			}
	}
}

double getAverage(const double array[], int Num_Months)
{
	double total = 0;
	double average;
	for (int count = 0; count < Num_Months; count++)
		total += array[count];
	average = total/Num_Months;
	return average;
}

double getLowest(const double array[], int Num_Months)
{
	double lowest;
	lowest = array[0];
	for (int count = 1; count < Num_Months; count++)
	{
		if (array[count] < lowest)
			lowest = array[count];
	}
	return lowest;
}

double getHighest(const double array[], int Num_Months)
{
	double highest;
	highest = array[0];
	for (int count = 0; count < Num_Months; count++)
	{
		if (array[count] > highest)
			highest = array[count];
	}
	return highest;
}

void rainOutput(const double array[], double average, double lowestfall, double highestfall)
{
	cout << fixed << showpoint << setprecision(2);
	cout << "The monthly rainfalls are:" << endl;
		for (int i=0;i<12;i++)
			cout << array[i] << " inches" << endl;
		cout << "The least rainfall is " << lowestfall << " inches." << endl;
		cout << "The average rainfall is " << average << " inches." << endl;
		cout << "The highest rainfall is " << highestfall << " inches." << endl;
		system("PAUSE");
		return;
}

EDIT: Looks like I got the idea wrong from the description. I need to return the month names from the highest and lowest functions, not the amount. I am unsure how to correlate the month names to the amount of rainfall. I would need two arrays for this, and I am trying to figure out how to do this. Thanks.
 

mackattk

Member
im not sure i understand what it needs to do that it isnt doing currently?

Attach a month to the highest and lowest rainfall on the rainOutput function. I am not sure how to do this. Right now all it does is output the highest and lowest values that are returned from the getLowest and getHighest functions.
 

nan0

Member
Attach a month to the highest and lowest rainfall on the rainOutput function. I am not sure how to do this. Right now all it does is output the highest and lowest values that are returned from the getLowest and getHighest functions.

You could do that with a vector.

Code:
vector<int> extrema(3, 0);
extrema[0] = month;
extrema[1] = high_val;
extrema[2] = low_val;

// If you are using C++11, this also works:

vector<int> extrema {month,high_val,low_val};

There are probably better/cleaner ways in C++, but I haven't used it in ages and it's my least favorite languages from those I know.
 
OK gaf, I'm in need of some SERIOUS help.

I'm taking a concurrency class, which is pretty cool, but the teacher insists that the projects are to be in scheme, despite the fact that everyone in the class insists that they don't know scheme, and that every single example in both of our 2 books is either in C or python. He also has spent 0 lectures teaching us any scheme syntax, or how to create threads in scheme, etc., and scheme help/documentation online is terrible.

Anyway, I had to take an unthreaded program that he wrote that creates a "planet" when you click, and then has a checkbox to make the plants orbit each other or stop orbiting.

We were supposed to make a version that puts all the calculation into one thread. I think he wants us to use thread-suspend and thread-resume, but I couldn't get these to work. Here's what I did using semaphores :

Code:
#lang racket



(require racket/gui)
(require racket/block)

;; Small 2d vector library for the Newtonian physics
(define (x v) (vector-ref v 0))
(define (y v) (vector-ref v 1))
(define (x! v value) (vector-set! v 0 value))
(define (y! v value) (vector-set! v 1 value))
(define (v* v value) (vector-map (lambda (x) (* x value)) v))
(define (v+ v w) (vector-map + v w))
(define (v- v w) (vector-map - v w))
(define (v-zero! v) (vector-map! (lambda (x) 0) v))
(define (v-dot v w) (let ((vw (vector-map * v w))) (+ (x vw) (y vw))))
(define (v-mag v) (sqrt (v-dot v v)))
(define sem (make-semaphore))


;; Planet object
(define planet%
  (class object%
    (public m p v calculate-force move draw)
    (init-field (mass 1)
                (position (vector 0 0 ))
                (velocity (vector 0 0 ))
                (force (vector 0 0 )))
    (define (m) mass)
    (define (p) position)
    (define (v) velocity)
    ;; Use Newton's law of gravitation.
    ;; I assume the gravitational constant is one
    (define (calculate-force planet-list)
      (v-zero! force)
      (for-each (lambda (other-planet)
                  (when (not (equal? this other-planet))
                    (let* ((direction (v- (send other-planet p) position))
                           (dist (max 1 (v-mag direction)))
                           (other-mass (send other-planet m))
                           (new-force (v* direction (/ (* mass other-mass) (* dist dist))))
                          )
                      (vector-map! + force new-force))))
                planet-list)
      )
    ;; Simple Euler integration of acceleration and velocity
    (define (move) 
      (let ((acc (v* force (/ 1.0 mass))))
        (vector-map! + velocity acc)
        (vector-map! + position velocity)))
    ;; Draw a circle 
    (define (draw dc) 
      (send dc set-brush brush)
      (send dc set-pen pen)
      (send dc draw-ellipse (x position) (y position) radius radius ))
    ;; Initialize to random velocity, mass, and color
    (x! velocity (random))
    (y! velocity (random))
    (set! mass (+ 1 (* 10 (random))))
    (define radius (* 5 (sqrt mass)))
    (define color 
      (let* ((r (random))
             (b (real->floating-point-bytes r 4)))
        (make-object color% (bytes-ref b 0) (bytes-ref b 1) (bytes-ref b 2) )))
    (define brush (make-object brush% color))
    (define pen (make-object pen% color))
    ;; Don't forget the super-new!
    (super-new)
    ))
;; Abstract the list-handling for a list of planets
(define planet-list%
  (class object%
    (public add-planet calculate-force move draw)
    (init-field (planets '()))
    (define (add-planet planet)
      (set! planets (cons planet planets)))
    (define (calculate-force)
      (for-each (lambda (planet)
                  (send planet calculate-force planets))
                planets))
    (define (move)
      (for-each (lambda (planet)
                  (send planet move))
                planets))
    (define (draw dc)
      (for-each (lambda (planet)
                  (send planet draw dc))
                planets))
    (super-new)
    )
  )
(define planet-list (new planet-list%))
    
;; The GUI
(define frame (new frame% 
                   (label "Planets")
                   (min-width 120)
                   (min-height 80)
                   ))
(send frame create-status-line)
(send frame show #t)

(define h-panel
  (new horizontal-panel%
       (parent frame)
       (stretchable-height #f)
       (style '(border))
       (border 2)))

(define run-checkbox
  (new check-box%
       (parent h-panel)
       (label "Run animation")
       (callback
        (lambda (button event)
          (cond
            [(send run-checkbox get-value)(semaphore-post sem)]
            [(not (send run-checkbox get-value)) (semaphore-wait sem)]
          
          

       )))
        ))

(define my-canvas%
  (class canvas%
    (override on-paint on-event)
    
    (define (on-paint)
      (let ((dc (send this get-dc))
            (w (send this get-width))
            (h (send this get-height)))
        (send dc clear)
        (send planet-list draw dc)
        ))
    (define (on-event event)
      (when (send event button-down?)
        (let ((x (send event get-x))
              (y (send event get-y)))
          (send frame set-status-text (format "Mouse at ~a ~a" x y))
          (send planet-list add-planet (new planet% (position (vector x y))))
          
          (send this refresh)))
      )
    (super-new)
    (send (send this get-dc) set-background (make-object color% 8 8 64))
    ))

(define canvas
  (new my-canvas%
       (parent frame)
       (style '(border))
       (min-width 640)
       (min-height 480)))

;; planet animator
(define thread-a (lambda ()
(let loop ()
  (semaphore-wait sem)
  (sleep/yield .1)
    (send planet-list calculate-force)
    (send planet-list move)
    (send canvas refresh)
    (semaphore-post sem)

  (loop))))

; this creates the thread-a and starts the program
(thread thread-a)

The next part of the assignment, we are supposed to make a thread for every single planet, which is started and stopped when the checkbox is clicked.

tl;dr threading in scheme HALP


my friend and i are laughing at you. sorry, this is just hilarious.
 

smiggyRT

Member
Java question, I'm getting a NullPointerException error and struggling to see where I'm going wrong here.

Basically I have to create an employee records thing and I'm adding these employees to an array then one by one displaying the contents of the array.

Code:
public class Controller {
	
	public static void main(String[] args) {
		
		Store store = new Store(100);
		System.out.println("Current size of the store is "+store.getCount());
		
		if (!store.isFull())
			store.addEmployee(new Employee());
		else
			System.out.println("Store is full");
		
		
		if (!store.isFull())
			store.addEmployee(new Employee("John", 'm', new Date(31, 10, 2006), "1", new Date(31, 10, 2006)));
		else
			System.out.println("Store is full");
		
		
		if (!store.isFull())
			store.addEmployee(new Employee("Jane", 'f', new Date(31, 11, 1986), "2", new Date(1, 1, 2006)));
		else
			System.out.println("Store is full");
		
		
		System.out.println("Current store size is "+store.getCount());
		store.displayAll((store.getCount())-1);
		
	}

}
Code:
import java.io.*;
import java.util.*;
public class Store {

	private int MAXSIZE; //array size
	private int count; //holds number of employees stored in array
	Person[] list;
	
	
//set default constructor for class
		public Store() {
			MAXSIZE = 100;
			count = 0;
		}
		
//constructor with max size specified
		public Store(int size) {
			MAXSIZE = size;
			count = 0;
			
		}
//returns current number of employees held in store
	public int getCount() {
		return count;
	}
	
//checks to see if array is full
	public boolean isFull() {
		return count == MAXSIZE;
	}
	

	
//create clone of another store
	public Store(Store other) {
		MAXSIZE = other.MAXSIZE;
		count = other.count;
		list = other.list;
	}
	
//method for adding an employee to the array
	public void addEmployee(Employee p) {
		list = new Person[MAXSIZE];
		list[count] = new Employee(p);
		count++;
	}
	
	public void displayAll(int i) {
		if (i >= 0) {
		System.out.println(list[i]);
		displayAll(i-1);
		
		}
	}
	
}
Code:
import java.io.*;
public class Employee extends Person {
	
	protected  String id, jobTitle;
	protected Date start;
	protected float salary;

//constructors
	public Employee() {
		id = jobTitle = "n/a";
		start = new Date();
		salary = 0;
	}
	
	public Employee(String nam, char sex, Date dob, String employeeId, Date jobStart) {
		name = nam;
		gender = sex;
		dateOfBirth = dob;
		id = employeeId;
		start = new Date(jobStart);
	}
	
//clone an employee, used to add an employee to the array
	public Employee(Employee other) {
		name = other.name;
		gender = other.gender;
		dateOfBirth = other.dateOfBirth;
		address = other.address;
		natInsceNo = other.natInsceNo;
		phoneNo = other.phoneNo;
		id = other.id;
		jobTitle = other.jobTitle;
		start = other.start;
		salary = other.salary;
	}
	
//setters
	public void setSalary(float aSalary) {
		salary = aSalary;
	}
	
	public void setJobTitle(String aJobTitle) {
		jobTitle = aJobTitle;
	}
	
//getters
	public String getJobTitle() {
		return jobTitle;
	}
	
//all employee information returned as a string
	public String toString() {
		String details = "Name - "+name+"\nEmployee ID - "+id+"\nJob Title - "+jobTitle+"\nStart Date - "+start+"\nSalary - "+salary;
		return details;
	}

}
Code:
import java.io.*;
public class Person {
	
	protected String name, address, natInsceNo, phoneNo;
	protected char gender;
	protected Date dateOfBirth;

//constructors
	public Person() {
		name = address = natInsceNo = phoneNo = "n/a";
		gender = ' ';
		dateOfBirth = new Date();
	}

//create clone of another person
	public Person(Person other) {
		name = other.name;
		address = other.address;
		natInsceNo = other.natInsceNo;
		phoneNo = other.phoneNo;
		gender = other.gender;
		dateOfBirth = other.dateOfBirth;
	}
	
	public Person(String aName, char sex, Date dob) {
		name = aName;
		address = natInsceNo = phoneNo = "n/a";
		gender = sex;
		dateOfBirth = dob;
	}
	
//setters
	public void setName(String aName) {
		name = aName;
	}
	
	public void setAddress(String add) {
		address = add;
	}
	
	public void setNatInsNo(String natNo) {
		natInsceNo = natNo;
	}
	
	public void setPhoneNo(String phone) {
		phoneNo = phone;
	}
	
//getters
	public String getName() {
		return name;
	}
	
	public String getAddress() {
		return address;
	}
	
	public String getNatInsNo() {
		return natInsceNo;
	}
	
	public String getPhoneNo() {
		return phoneNo;
	}
	
//check if a person is the same as another person
	public boolean isEqual(Person other) {
		return name == other.name &&
				natInsceNo == other.natInsceNo &&
				 dateOfBirth == other.dateOfBirth;
	}
	
//all of a persons details to be returned as a string
	public String toString() {
		String details = "Name : "+name+"\nGender : "+gender+"\nDate of Birth : "+dateOfBirth+"\nAddress : "+address+"\nNational Insure Number : "+natInsceNo+"\nPhone Number : "+phoneNo;
		return details;
	}
}

In the console Jane's information is displayed but the first 2 just return null and I can't see why.
 
Java question, I'm getting a NullPointerException error and struggling to see where I'm going wrong here.

Basically I have to create an employee records thing and I'm adding these employees to an array then one by one displaying the contents of the array.

In the console Jane's information is displayed but the first 2 just return null and I can't see why.

The problem is here:

Code:
public void addEmployee(Employee p) {
		list = new Person[MAXSIZE];
		list[count] = new Employee(p);
		count++;
	}


Whenever you're adding an employee, you're making an entirely new array.
 

shintoki

sparkle this bitch
I'm extremely new to programming, so you have to explain this very... low.
// This is a C++ comment line
#include <iostream> //required for basic I/O

using namespace std;

int main()
{
//declared variables
double base = 0.0;
double height = 0.0;
double area = 0.0;

//input items
cout << " 1: ";
cin >> base;
cout << " 1.5: ";
cin >> height;

//calculate area
area = 1/2*base*height

//calucate
cout << " Your area is: " << area << end1;

return 0;
//end of main function

}

The final cout is highlighted with red, I'm assuming that is were the error is with my debug. The program is supposed to calculate the area of a triangle.

Anyone got some help? I've been googling a few of the step ups and choose this one.

When I debug and try to boot it up, it says "System can not find file specified"
 
I'm extremely new to programming, so you have to explain this very... low.


The final cout is highlighted with red, I'm assuming that is were the error is with my debug. The program is supposed to calculate the area of a triangle.

Anyone got some help? I've been googling a few of the step ups and choose this one.

When I debug and try to boot it up, it says "System can not find file specified"
From the looks of things, you forgot a semicolon at the end of the line that is calculating area. Additionally, your area calculation will always result in 0. Having just 1/2 calculates an integer, which means that instead of 0.5, it will truncate the result to be 0. Making it 1.0/2.0 makes it clear the calculation should result in a double. (Or better yet, replace 1/2 with 0.5)

#include <iostream> //required for basic I/O

using namespace std;

int main()
{
//declared variables
double base = 0.0;
double height = 0.0;
double area = 0.0;

//input items
cout << " 1: ";
cin >> base;
cout << " 1.5: ";
cin >> height;

//calculate area
area = 1.0/2.0*base*height;

//calucate
cout << " Your area is: " << area << endl;

return 0;
//end of main function

}
 

Leucrota

Member
I'm extremely new to programming, so you have to explain this very... low.


The final cout is highlighted with red, I'm assuming that is were the error is with my debug. The program is supposed to calculate the area of a triangle.

Anyone got some help? I've been googling a few of the step ups and choose this one.

When I debug and try to boot it up, it says "System can not find file specified"

From the looks of things, you forgot a semicolon at the end of the line that is calculating area. Additionally, your area calculation will always result in 0. Having just 1/2 calculates an integer, which means that instead of 0.5, it will truncate the result to be 0. Making it 1.0/2.0 makes it clear the calculation should result in a double. (Or better yet, replace 1/2 with 0.5)

In your text editor, you may have everything indented good, but if you don't, you should really learn how to start indenting properly so that the code is more readable. As a budding programmer as well, I can tell you point blank it makes debugging the code so much easier.
 

GrizzNKev

Banned
I need some serious help. I'm writing a very small program in C that grabs 100 y-values from a sin wave between 0 and 2*pi, then converts them into Q1.15 format. It's part of my audio programming course.

My assignment also involved verifying the sizes of certain data types on the PIC chip we're using, which of course was trivial.

According to Wikipedia,

Float to Q
To convert a number from floating point to Qm.n format:
Multiply the floating point number by 2^n
Round to the nearest integer

So that's what I did.

Code:
int16_t main(void)
{

    /* Configure the oscillator for the device */
    ConfigureOscillator();

    /* Initialize IO ports and peripherals */
    InitApp();

    int a;
    long b;
    double c;
    int i;

    const double twopi = 2 * 3.14159265359;
    const double x = twopi / 100;
    double currentsincap[100];
    signed int sinarray[100];

    a = sizeof(a);
    b = sizeof(b);
    c = sizeof(c);

    sinarray[0] = 0;

    for(i = 1; i < 100; i++)
    {
        currentsincap[i] = sin(x * i);
        currentsincap[i] *= 32768;

        sinarray[i] = (signed int)(currentsincap[i] - 1);

    }
}

When I check what's stored in my array, I get exactly what I expect from 0 - 50: it starts at zero, follows the curve up to .9999, then back down to zero. But when I get to negative numbers, it jumps to -2 when it should be -.001, rises to -1 rather than falling to -1, then falls back to -2 rather than rising to 0.

Did something go wrong during the conversion to Q15?
 

Argyle

Member
I need some serious help. I'm writing a very small program in C that grabs 100 y-values from a sin wave between 0 and 2*pi, then converts them into Q1.15 format. It's part of my audio programming course.

My assignment also involved verifying the sizes of certain data types on the PIC chip we're using, which of course was trivial.

According to Wikipedia,



So that's what I did.

Code:
int16_t main(void)
{

    /* Configure the oscillator for the device */
    ConfigureOscillator();

    /* Initialize IO ports and peripherals */
    InitApp();

    int a;
    long b;
    double c;
    int i;

    const double twopi = 2 * 3.14159265359;
    const double x = twopi / 100;
    double currentsincap[100];
    signed int sinarray[100];

    a = sizeof(a);
    b = sizeof(b);
    c = sizeof(c);

    sinarray[0] = 0;

    for(i = 1; i < 100; i++)
    {
        currentsincap[i] = sin(x * i);
        currentsincap[i] *= 32768;

        sinarray[i] = (signed int)(currentsincap[i] - 1);

    }
}

When I check what's stored in my array, I get exactly what I expect from 0 - 50: it starts at zero, follows the curve up to .9999, then back down to zero. But when I get to negative numbers, it jumps to -2 when it should be -.001, rises to -1 rather than falling to -1, then falls back to -2 rather than rising to 0.


Did something go wrong during the conversion to Q15?

So, I have no idea what Q format is. But you're supposed to round to the nearest integer you say? Your cast to int is simply truncating the number...I think adding .5 before the cast should work? I'm lying in bed, on my phone and I'm tired...didn't even see the minus 1 at first on my phone's screen, what is that for?

Edit: ahh, fixed point. Haven't used that in a long time...
 

Ambitious

Member
I'm extremely new to programming, so you have to explain this very... low.


The final cout is highlighted with red, I'm assuming that is were the error is with my debug. The program is supposed to calculate the area of a triangle.

Anyone got some help? I've been googling a few of the step ups and choose this one.

When I debug and try to boot it up, it says "System can not find file specified"

A comment unrelated to your problem: Redundant/unneccessary comments are considered bad style. For example:

//calculate area
area = 1/2*base*height

Why yes, I can see that it calculates the area. That comment only clutters the code.

I guess your teacher or professor told you that you should comment as much of your code as possible? Because my teacher said this back then. The opposite is actually true, try to write your code as clean and simple as possible so no one (including yourself) needs comments to understand it.

But if it helps you as you're a beginner, no problem. Just some advice for your future career.
 

leroidys

Member
I'd like to help you out but I don't know enough about Scheme to offer any useful insights.

Thanks, neither do I :(

The teacher has a religious devotion to the language, and since "when I teach (prereq class) I always teach my students scheme*" we are supposed to automacigally know it.

*He hasn't taught the prereq class in almost two years.
 

mackattk

Member
I made some progress on my code. The only thing I have left to do is try to link the array of the amount of rainfall to the array of the months. I am not exactly sure how to do this, because the rainfall is an array of doubles, and the months is an array of strings.

Code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

void getMonths(double[], string[], int);
double getAverage(const double[], int);
double getLowest(const double[], int);
double getHighest(const double[], int);
void rainOutput(const double [], string[], double, string, string);

int main()
{
	const int Num_Months = 12;
	string lowestmonth, highestmonth;
	double rainFall[Num_Months], average;
	int	lowestfall,	highestfall;
	string monthNames[] = {"January","Febuary","March","April","May","June",
						"July","August","September","October","November","December"};

	getMonths(rainFall, monthNames, Num_Months);
	average=getAverage(rainFall, Num_Months);
	lowestfall=getLowest(rainFall, Num_Months);
	highestfall=getHighest(rainFall, Num_Months);

	lowestmonth=monthNames[lowestfall];
	highestmonth=monthNames[highestfall];

	rainOutput(rainFall, monthNames, average, lowestmonth, highestmonth);
	return 0;
	system("PAUSE");
}

void getMonths(double rainFall[], string monthNames[], int Num_Months)
{
	int index;
	for(index = 0; index <=Num_Months -1; index++)
	{
		cout << "Enter rainfall for "
			<< monthNames[index] << ": ";
			cin >> rainFall[index];
			while (rainFall[index] < 0)
			{
				cout << "Please enter a positive amount of rain" << endl;
				cin >> rainFall[index];
			}
	}
}

double getAverage(const double array[], int Num_Months)
{
	double total = 0;
	double average;
	for (int count = 1; count < Num_Months; count++)
		total += array[count];
	average = total/Num_Months;
	return average;
}

double getLowest(const double array[], int Num_Months)
{
	double lowest;
	int lowcount=0;
	lowest = array[0];
	for (int count = 1; count < Num_Months; count++)
	{
		if (array[count] < lowest)
                {
                        lowest=array[count];
			lowcount = count;
                }
	}
	return lowcount;
}

double getHighest(const double array[], int Num_Months)
{
	double highest;
	int highcount=0;
	highest = array[0];
	for (int count = 0; count < Num_Months; count++)
	{
		if (array[count] > highest)
               {
                        highest=array[count];
			highcount=count;
               }
	}
	return highcount;
}

void rainOutput(const double array[], string monthNames[], double average, string lowestmonth, string highestmonth)
{
	cout << fixed << showpoint << setprecision(2);
	cout << "The monthly rainfalls are:" << endl;
		for (int i=0;i<12;i++)
		{
			cout << setw(12) << left << monthNames[i] << ": " << array[i] << " inches" << endl;
		}
		cout << "The least rainfall is " << lowestmonth << endl;
		cout << "The highest rainfall is " << highestmonth  << endl;
		cout << "The average rainfall is " << average << " inches." << endl;
		system("PAUSE");
		return;
}
 

leroidys

Member
I made some progress on my code. The only thing I have left to do is try to link the array of the amount of rainfall to the array of the months. I am not exactly sure how to do this, because the rainfall is an array of doubles, and the months is an array of strings.

Code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

void getMonths(double[], string[], int);
double getAverage(const double[], int);
int getLowest(const double[], int);
int getHighest(const double[], int);
void rainOutput(const double [], string[], double, string, string);

int main()
{
	const int Num_Months = 12;
	string lowestmonth, highestmonth;
	double rainFall[Num_Months],
		average,
		lowestfall,
		highestfall;
	int lowest, highest;
	string monthNames[] = {"January","Febuary","March","April","May","June",
						"July","August","September","October","November","December"};

	getMonths(rainFall, monthNames, Num_Months);
	average=getAverage(rainFall, Num_Months);
	lowestfall=getLowest(rainFall, Num_Months);
	highestfall=getHighest(rainFall, Num_Months);

	lowestmonth=monthNames[lowest];
	highestmonth=monthNames[highest];

	rainOutput(rainFall, monthNames, average, lowestmonth, highestmonth);
	return 0;
	system("PAUSE");
}

void getMonths(double rainFall[], string monthNames[], int Num_Months)
{
	int index;
	for(index = 0; index <=Num_Months -1; index++)
	{
		cout << "Enter rainfall for "
			<< monthNames[index] << ": ";
			cin >> rainFall[index];
			while (rainFall[index] < 0)
			{
				cout << "Please enter a positive amount of rain" << endl;
				cin >> rainFall[index];
			}
	}
}

double getAverage(const double array[], int Num_Months)
{
	double total = 0;
	double average;
	for (int count = 0; count < Num_Months; count++)
		total += array[count];
	average = total/Num_Months;
	return average;
}

int getLowest(const double array[], int Num_Months)
{
	double lowest;
	lowest = array[0];
	for (int count = 1; count < Num_Months; count++)
	{
		if (array[count] < lowest)
			lowest = count;
	}
	return lowest;
}

int getHighest(const double array[], int Num_Months)
{
	double highest;
	highest = array[0];
	for (int count = 0; count < Num_Months; count++)
	{
		if (array[count] > highest)
			highest = count;
	}
	return highest;
}

void rainOutput(const double array[], string monthNames[], double average, string lowestmonth, string highestmonth)
{
	cout << fixed << showpoint << setprecision(2);
	cout << "The monthly rainfalls are:" << endl;
		for (int i=0;i<12;i++)
			cout << setw(12) << left << monthNames[i] << ": " << array[i] << " inches" << endl;
		cout << "The least rainfall is " << lowestmonth << endl;
		cout << "The highest rainfall is " << highestmonth << endl;
		cout << "The average rainfall is " << average << " inches." << endl;
		system("PAUSE");
		return;
}

There's a bunch of ways you could do this, but I would probably make a Struct that contains both a string for the month name and a float for the rainfall. Then you can just call array[pos].month and array[pos].rainfall.
 

mackattk

Member
There's a bunch of ways you could do this, but I would probably make a Struct that contains both a string for the month name and a float for the rainfall. Then you can just call array[pos].month and array[pos].rainfall.

I am making progress and I almost have it. The only problem I am having now is that the highest month is always december, I am looking over my code and the function for the highest count seems fine.

The lowest month is structured similar, and it is working fine.

Code:
double getHighest(const double array[], int Num_Months)
{
	double highest;
	int highcount=0;
	highest = array[0];
	for (int count = 0; count < Num_Months; count++)
	{
		if (array[count] > highest)
			highcount = count;
	}
	return highcount;
}

I am glad I am making some progress.
 
I am making progress and I almost have it. The only problem I am having now is that the highest month is always december, I am looking over my code and the function for the highest count seems fine.

The lowest month is structured similar, and it is working fine.

I am glad I am making some progress.

You're just forgetting to update highest, so the returned element will always be the last one in the array that is higher.

Code:
double getHighest(const double array[], int Num_Months)
{
	double highest;
	int highcount=0;
	highest = array[0];
	for (int count = 0; count < Num_Months; count++)
	{
		if (array[count] > highest)
                {
			highcount = count;
                        [B]highest = array[count];[/B]
                }
	}
	return highcount;
}
 

mackattk

Member
You're just forgetting to update highest, so the returned element will always be the last one in the array that is higher.

Code:
double getHighest(const double array[], int Num_Months)
{
	double highest;
	int highcount=0;
	highest = array[0];
	for (int count = 0; count < Num_Months; count++)
	{
		if (array[count] > highest)
			highcount = count;
                        [B]highest = array[count];[/B]
	}
	return highcount;
}

Thanks, I tried that. I think there is something else going funky with my code.
 
Thanks, I tried that. I think there is something else going funky with my code.

Code:
int main()
{
	const int Num_Months = 12;
	string lowestmonth, highestmonth;
	double rainFall[Num_Months],
		average,
		lowestfall,
		highestfall;
	int lowest, highest;
	string monthNames[] = {"January","Febuary","March","April","May","June",
						"July","August","September","October","November","December"};

	getMonths(rainFall, monthNames, Num_Months);
	average=getAverage(rainFall, Num_Months);
	lowestfall=getLowest(rainFall, Num_Months);
	highestfall=getHighest(rainFall, Num_Months);

	lowestmonth=monthNames[lowest];
	highestmonth=monthNames[highest];

	rainOutput(rainFall, monthNames, average, lowestmonth, highestmonth);
	return 0;
	system("PAUSE");
}

I don't know how you're getting some result because you never set the variable highest to anything here

edit: and lowest for that matter
 

mackattk

Member
I don't know how you're getting some result because you never set the variable highest to anything here

edit: and lowest for that matter

I updated all my code in my previous post. Some of that was changed along the way.

Got it working.. thanks for all your help. This is going to be a rough battle for me trying to get some of these concepts through my head.
 
Does anyone use something other than Eclipse for Android? Also, can anyone recommend any tutorials for Android apps?

I made a simple app a few years ago, so I wanted to see if there were any changes in Android development other than the new features in the OS.
 

nan0

Member
Does anyone use something other than Eclipse for Android? Also, can anyone recommend any tutorials for Android apps?

I made a simple app a few years ago, so I wanted to see if there were any changes in Android development other than the new features in the OS.

It's been a year since I worked with Android and Eclipse, but IntelliJ supports Android, and I think it was possible with Netbeans and Visual Studio too, though a bit hacky.
 

snorggy

Member
not explicitly coding related but... is .net magazine a good resource? I've been thinking of subscribing, but it is $130/year for the subscription so I'm basically looking for some assurances that it's worth it. Anyone read or subscribe to it? Thoughts?
 

PGamer

fucking juniors
Do any of you guys have any experience working with the Kinect Windows SDK? I'm trying to do something I thought would be relatively simple (have a player make a walking motion to move a character forward in Unity 3D) but I'm starting to feel I'm in over my head.
 

jokkir

Member
Can someone help me out here? I'm not sure how to do this ><.

A part of a program I have to write is a function that receives a string of random characters separated into "lines". Each line consists of 60 characters each. The string of random characters looks like this:

Code:
"L4J 7G23?80Y#!#@?S:D$8.FCZ0%R;K6$X]8K1NfTV=7RM: J47r;9K-WT7T\n\
 XKEEw@CO5M.b@3NSM^ATE8OO?_J2)--$+1C; %K!%_3#]sWYADK1Z?Q11X;M\n\
 1VE<6:4JC!QBrweY3T+1)%W+.AQWUO[]7IBS9C,!<!7(<TK54T=&M%F:!2,4\n\
 OQ2_9]q*=E2]$QB*.90:=NT!-I_BR8R.$.LTd(wI?Q%.GQPI:3)8GT[5G5r<\n\
 +811_$,I[)&KQr2AZV-FME4J#VSG7(LV?%X=)4+6[+*W62Q6@H)%!#(MEEH,\n";

The \n indicates whether it's a new line or not but is still in the same string. What I was thinking was I should store these lines into a two dimensional array of something like

Code:
lines[60][line_counter];

And then write something that can read how many lines there are in that string because apparently, that string it can hold can have as many lines or little lines. I wrote that line_counter function then stuck here. How would you pass that two dimensional array "lines[60][line_amount];" to a function since the second value will change depending on how many lines there are.

Currently, my code looks like this:
Code:
#include <stdio.h>
#include <string.h>

int testFunction(char rawData[]);
int line_counter(char rawData[]);
void store_line_data(char *lines[][line_amount], char rawData[], int line_amount);
int countLetters(char rawData[]);

int main(){
	printf("Hello World!\n");

	char rawData[1000] = "L4J 7G23?80Y#!#@?S:D$8.FCZ0%R;K6$X]8K1NfTV=7RM: J47r;9K-WT7T\n\
 				  XKEEw@CO5M.b@3NSM^ATE8OO?_J2)--$+1C; %K!%_3#]sWYADK1Z?Q11X;M\n\
 				  1VE<6:4JC!QBrweY3T+1)%W+.AQWUO[]7IBS9C,!<!7(<TK54T=&M%F:!2,4\n\
 				  OQ2_9]q*=E2]$QB*.90:=NT!-I_BR8R.$.LTd(wI?Q%.GQPI:3)8GT[5G5r<\n\
				  +811_$,I[)&KQr2AZV-FME4J#VSG7(LV?%X=)4+6[+*W62Q6@H)%!#(MEEH,\n";
				  
	testFunction(rawData);
	
	return 0;
}

int testFunction(char rawData[]){
	int output = 0;
	int line_amount = 0;
	
	line_amount = line_counter(rawData);
	
	char lines[60][line_amount];
	
	store_line_data(&lines, rawData, line_amount);
	output = countLetters(rawData);

	printf("Line_amount: %d", line_amount);
	printf("Output: %d", output);

	return 0;
}

int line_counter(char rawData[]){
	int i = 0;
	int line_counter = 0;
	int len = strlen(rawData);

	/*Determines how many lines are in rawData*/
	for(i = 0; i < len; i++){
		if(rawData[i] == '\n'){
			line_counter++;
		}
		else{
			i = i; /*i value remains the same*/
		}
	}
	return line_counter;
}

void store_line_data(char *lines[][line_amount], char rawData[], int line_amount){
	printf("Hello");
}

int countLetters(char rawData[]){
	int return_value = 0;
	
	return_value = strlen(rawData);
	
	return return_value;
}

but as you can guess the lines[][line_amount] doesn't work (or maybe I'm coding it wrong). I'm thinking I'll need it because I need to analyze the lines again to see for matches on the next line and so on. Am I doing this right?

Also, is my logic right or should I go about it a different way? My teacher told us we might not even need the two dimensional array or something.
 

GrizzNKev

Banned
I just ran basically your exact code and it comes out cleanly. From 50 - 75 it's a smooth descent to -1 and then back up to 0 again. There must be something going on in the h/w platform I think? Have you tested the code on an x86 cpu?

Yeah I figured out the next day I had the output chart interpreting the values wrong. It was fine when I looked at the hex. lol oops
 

Zeppelin

Member
Can someone help me out here? I'm not sure how to do this ><.

As you say, the number of lines will change. And thus you will need to allocate the memory for the two dimensional array dynamically. malloc is what you use for this.

Code:
line_amount = line_counter(rawData);
char* lines = malloc(line_amount * 60);
if (lines == NULL)
   // We're fucked, handle this somehow

The call to malloc will allocate memory for line_amount strings of length 60 chars. If malloc fails (it rarely does) it will return a NULL pointer. You should always check for this.

Then you can for instance access the... I don't know... the third line like this:

Code:
for (int i = 0; i < 60; ++i) {
   putc(lines((3 * 60) + i), stdout); // Prints 3rd line to stdout
}

And remember to free the memory you allocated by calling free when you're done with it:
Code:
free(lines);
lines = NULL;

This gives it back to the operating system (at least kind of...) for it to give to someone else in need of it. If you don't do this that memory will remain unusable for the duration of your program run.

Edit: Not really sure what you're trying to do though...
 
Can someone help me out here? I'm not sure how to do this ><.

A part of a program I have to write is a function that receives a string of random characters separated into "lines". Each line consists of 60 characters each. The string of random characters looks like this:

What exactly are you supposed to output? Just the number of lines? What else do you need to output?

I'm just not seeing the point of a 2D array here, because it looks like the only you need to output things that don't need a 2D array.

And then write something that can read how many lines there are in that string because apparently, that string it can hold can have as many lines or little lines. I wrote that line_counter function then stuck here. How would you pass that two dimensional array "lines[60][line_amount];" to a function since the second value will change depending on how many lines there are.

For the argument it would just be char[][] lines, and then its up to you to find out how many rows/etc there are with length checks, but you don't even to do that since you're passing along line_amount as well.
 

jokkir

Member
What exactly are you supposed to output? Just the number of lines? What else do you need to output?

I'm just not seeing the point of a 2D array here, because it looks like the only you need to output things that don't need a 2D array.

I was trying to separate the lines and storing them in 2D arrays because a later thing I have to code is to find a character in the same position, in the next line. So if it finds a "3" in the first line in the 25th position, it'll check the second line for "3" in the 25th position.

But maybe there's a different way of doing it?
 
I was trying to separate the lines and storing them in 2D arrays because a later thing I have to code is to find a character in the same position, in the next line. So if it finds a "3" in the first line in the 25th position, it'll check the second line for "3" in the 25th position.

But maybe there's a different way of doing it?

Yeah, there is. It's pretty simple to figure it out, so I'll leave it up to you. You only need the initial array of characters you start out with. Just keep in mind that you know that all the lines are the same length.
 

jokkir

Member
Yeah, there is. It's pretty simple to figure it out, so I'll leave it up to you. You only need the initial array of characters you start out with. Just keep in mind that you know that all the lines are the same length.

Ah, alright. I thought of several ways of doing this but I thought this would be the best way of doing it. I'll get back with results :p
 

FerranMG

Member
Does anybody know what can be wrong with this in C++?

char* GetFileExt(const char* FileName)
{
char* ext = (char*)FileName;
while(*ext++ != '.');
return ext;
}

I have no clue and I need it for a test.
 

Ambitious

Member
Does anybody know what can be wrong with this in C++?

char* GetFileExt(const char* FileName)
{
char* ext = (char*)FileName;
while(*ext++ != '.');
return ext;
}

I have no clue and I need it for a test.

The two things I can think of:

1) It just returns the substring starting from the first dot. A filename can contain several of them, so for those it returns more than only the extension.
2) No check for the end of the string. If there's no one in the filename, the loop just keeps running and evaluating addresses until it encounters a dot.
 
Does anybody know what can be wrong with this in C++?

char* GetFileExt(const char* FileName)
{
char* ext = (char*)FileName;
while(*ext++ != '.');
return ext;
}

I have no clue and I need it for a test.

Unless you're leaving details out of the question, it'll run past the end of the string if no instances of a period are found. Also, you're not guaranteed that the function argument FileName, and consequently ext, even points to anything so you may end up dereferencing in areas of memory that aren't accessible by your program. It's a fantastic recipe for a segfault either way.
 

Minamu

Member
Can anyone tell me how to fix this problem? I'm trying to change my XNA code so that bomb placement is synced between windowed and full screen:

Code:
		public void generateLightBombs(List<BaseObject> list)
		{
			Player player = (Player)list[0];
			Vector2 playerPosition = player.mPosition;
			[B]Vector2 direction = new Vector2(Mouse.GetState().X - 400, Mouse.GetState().Y - 240);[/B]
			direction.Normalize();

			if(0 < player.Bomb && Keyboard.GetState().IsKeyDown(Keys.B) && pressedKey.IsKeyUp(Keys.B))
			{
				list.Add(new LightBomb(Color.Yellow, new Rectangle((int)(playerPosition.X - direction.X * 100.0f), 
(int)(playerPosition.Y - direction.Y * 1000.0f), 10, 10)));
				player.Bomb--;
			}
			pressedKey = Keyboard.GetState();
		}

I assume the bolded is the problem with the hard coded numbers and I'm supposed to connect the viewport size somehow? I basically want the bombs my space ships drop to always end up behind the ship at a fixed distance no matter what direction the ship is facing (which depends on where the mouse cursor is).
 

FerranMG

Member
The two things I can think of:

1) It just returns the substring starting from the first dot. A filename can contain several of them, so for those it returns more than only the extension.
2) No check for the end of the string. If there's no one in the filename, the loop just keeps running and evaluating addresses until it encounters a dot.

Unless you're leaving details out of the question, it'll run past the end of the string if no instances of a period are found. Also, you're not guaranteed that the function argument FileName, and consequently ext, even points to anything so you may end up dereferencing in areas of memory that aren't accessible by your program. It's a fantastic recipe for a segfault either way.

Got it, thanks a lot!
 

Bruiserk

Member
EDIT: fixed error 1.

VHDL question:

library IEEE;
use IEEE.std_logic_1164.all;
use work.all;

entity FP_MUL is
port(clk, mpy : in std_logic;
x, y : in std_logic_vector(15 downto 0);
rdy : out std_logic;
p : out std_logic_vector(15 downto 0));
end FP_MUL;

architecture behav of FP_MUL is
type state is (INIT, S0, S1, S2, S3, S4, S5);
signal vld, req : std_logic;
signal zero : boolean;
signal prod : std_logic_vector (15 downto 0);
signal new_state: state;
signal p1, p2 : std_logic_vector(7 downto 0);
begin

MPY: MPY8
port map(vld => vld, req => req, x => p1, y => p2, prod => prod, clk => clk);
-- state transition process:
process is
variable curr_state: state := INIT;
begin
if clk = '1' then
case curr_state is
when INIT =>
if mpy = '1' then curr_state := S0;
end if;
when S0 =>
curr_state := S1;
when S1 =>
if zero then curr_state := S5;
else curr_state := S2;
end if;
when S2 =>
if vld = '0' then curr_state := S2;
elsif (prod(15) AND vld) = '1' then curr_state := S3;
elsif (NOT prod(15) AND vld) = '1' then curr_state := S4;
end if;
when S3 =>
if mpy = '0' then curr_state := INIT;
end if;
when S4 =>
if mpy = '0' then curr_state := INIT;
end if;
when S5 =>
if mpy = '0' then curr_state := INIT;
end if;
end case;
end if;
new_state <= curr_state;
wait on clk;
end process;

-- asserted outputs process:
process is
variable p_val, XR, YR : std_logic_vector(15 downto 0);
begin
case new_state is
when INIT =>
p_val := X"0000"; rdy <= '1';
when S0 =>
XR := x; YR := y; zero <= (x = X"0000") OR (y = X"0000");
when S1 =>
p1 <= '1'&XR(6 downto 0); p2 <= '1'&YR(6 downto 0);
if zero then req <= '0';
else req <= '1';
end if;
when S3 =>
p_val(15) := XR(15) XOR YR(15);
p_val(14 downto 7) := (XR(14 downto 7) + YR(14 downto 7)) - "11111110"; --HERE
p_val(6 downto 0) := prod(14 downto 8);
rdy <= '1';
when S4 =>
p_val(15) := XR(15) XOR YR(15);
p_val(14 downto 7) := (XR(14 downto 7) + YR(14 downto 7)) - "11111111"; --HERE
p_val(6 downto 0) := prod(13 downto 7);
rdy <= '1';
when S5 =>
rdy <= '1';
end case;
p <= p_val; -- deliver output values to output port
wait on new_state; -- sensitivity list to restart process
end process;
end behav;


2) error line 73: incompatible types for arithmetic operator: LHS=std_logic_vector!37, RHS=std_logic_vector!40
3)error line 78: incompatible types for arithmetic operator: LHS=std_logic_vector!49, RHS=std_logic_vector!52

I have no clue why 2 and 3 are errors, I'm just adding two std_logic_vectors together.
 
Top Bottom