Labdabeta 182 Posting Pro in Training Featured Poster

It stops working because you have no code in those sections. If you choose 'B' you will execute this code:

else if (choice== 'B' || choice=='b') {

}

Which of course does nothing. Similarly after you create your arrays you don't do anything with them, so again it stops working.

Meanwhile I doubt you are intended to manually enter a bunch of numbers. You are likely supposed to generate them. To generate a random number between 'low' and 'high' you can do this:

int random = (rand() % (high-low)) + low

You can google search for "rand() C++" for more information.

Labdabeta 182 Posting Pro in Training Featured Poster

First of all the code for (a=4; a<5; a=a++) is undefined behaviour, you probably meant for (a=4; a<5; a++) which 'loops' a from 4 to 5 (essentially just running the loop once on the value a=4.

To use a value found inside the loop outside of it, it must be declared outside of it. Therefore your intended code was likely:

while (1) {
    <type> result;
    for (...) {
        ...
        result = ...;
    }
    //use result here all you want
}
Labdabeta 182 Posting Pro in Training Featured Poster

By hand.

What they did was they wrote out the code of the compiler in some slightly-higher language. Then they manually went through the code and compiled it themselves. Once that was done they could use the compiler to compile any future sources.

New compilers would then be 'bootstrapped' using old compilers by writing their code in a language for which a compiler already existed.

Labdabeta 182 Posting Pro in Training Featured Poster

Judging by your code it looks like you are doing Android development and trying to pass data from one activity to another. Due to the nature of Android activities (multithreaded, and can be GC'ed at any moment if, e.g. you get a phone call) you can't deal with passing data between them any of the normal java ways.

This leaves you with a few options which are easily googled for as "Android pass data between activities" or similar.

The following is a summary of the most common techniques.

Option 1: Application-Global values

This is useful if most/all of your activities will require access to the data. To implement it create a class that extends 'Application' and add the class name to the manifest under the <Application> tag. Inside this class you can have public static variables which can be accessed from any activity using getApplicationContext(). Here is an example:

class GlobalApplication extends Application {
    public static int value;
}

class SettingsActivity extends AppCompatActivity { 
    @Override
    protected static void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GlobalApplication me = (GlobalApplication)getApplicationContext();

        me.value = 1;
    }
}

class MainActivity extends AppCompatActivity {
    @Override
    protected static void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GlobalApplication me = (GlobalApplication)getApplicationContext();

        Log.d("Global value is: " + me.value);
    }
}
Option 2: Passing data through intents

If your first activity creates the second via an intent, you can add data to the intent to move values. This is preferred over creating an Application if it can be done. Here is an example:

JamesCherrill commented: Great contribution and clarifies many issues. Thanks. +15
Labdabeta 182 Posting Pro in Training Featured Poster

First of all that is C++, not C. Second your problem description is poor, however I think I understand what you are after.

Of interest is this code snippet:

//This code returns the n'th cycle of string s
std::string tmp;
for (int i=0; i<s.length(); ++i)
    tmp+=s[(i+n)%s.length()];

The way it works is by starting at an arbitrary position, then 'wrapping-around' back to the start of the string using the modulo operator.

If you get some code to compile, but its giving the wrong result, then maybe we can help you some more.

Stuugie commented: Good on you for figuring this out... +6
Labdabeta 182 Posting Pro in Training Featured Poster

In java, x<<y shifts x y bits to the left. x>>y arithmetically shifts x y bits to the right. x>>>y logically shifts x y bits to the right.

These operations are invaluable when you need to manipulate individual bits of a value.

For example, lets say you are using a bitmask to store 10 booleans in one integer. You can use | (or) to 'set' a bit, & (and) to 'clear' a bit, and ^ (xor) to swap a bit. However, to actually use these operations you would want to have access to the bits. You could do this manually: x|0x10 to set bits 2 and 4. However, bitshift operators let you do this generically: x|(1<<2)|(1<<4) also sets bits 2 and 4. As you can tell, the second version lends itself very nicely to being put into a method, while the first version does not.

There are many more uses of the shift operators in some advanced algorithms, since many of them use the fact that any number has a binary representation to decompose the number into its components (by stripping 1's and bitshifting right). For example you can fairly quickly calculate the remainder of a number by using the method of squaring.

Labdabeta 182 Posting Pro in Training Featured Poster

The issue is that localtime and localtime_s are slightly different. The _s stands for safe, it is a memory safe version of localtime. As such it does not create it's own tm* to return, rather you have to send it one. The correct code would be:

time_t now = time(0);
tm ltm;
localtime_s(&ltm,&now);
Labdabeta 182 Posting Pro in Training Featured Poster

This is one of those sneaky bugs. Basically it is telling you that if you declare a variable in the for loop, it only lasts as long as the for loop. At first glance it looks like you only ever use 'n' inside your loop. You are wrong. Let me re-write your code with some different whitespace-ing and you will see why:

// loop to generate audio samples
for(int n=0; n < length; n++) //where n is the step |Start of For loop
    int t = n/freq; //t/freq                        |End of For loop


{//random unnecessary block
    value = amp*sin(2*pi*freq*t);
    write_CSV(n, value, fp);
    cout << n << "\t" << value <<"\n";
}

The reason for this is that loops, and if statements, only last for 1 statement (IE: until the first semi-colon). This would make them really hard to use, except that C++ provides Blocks. Basically any time you say {/*code here*/} it takes all of your code and turns it into one statement. This is true of every time you use the curly braces (as far as I know). However functions often still require them (my compiler doesn't, but ideone does).

Thus the fix is simple: move line 22 into the block:

// loop to generate audio samples
for(int n=0; n < length; n++) //where n is the step |Start of For loop
{
int t = n/freq; //t/freq
value = amp*sin(2*pi*freq*t);
write_CSV(n, value, fp);
cout << n << "\t" << value <<"\n";
} //|End of For loop …
ddanbe commented: Fine eye! +15
Ancient Dragon commented: nice explanation +14
Labdabeta 182 Posting Pro in Training Featured Poster

You need to ensure that all 3 files will be included in your project. You have to set it up so that first samclass.cpp is compiled, creating samclass.o. Then main is compiled. When main compiles and sees samclass.h with undefined functions it will look for the object file and use it.

From your title it looks like you might be using Code::Blocks. If this is the case you should create a project and select Project->Add Files to ensure that all 3 files are accounted for.

Labdabeta 182 Posting Pro in Training Featured Poster

There are quite a few issues with your code... I will go through them one by one.

1) Invalid entry point

void main
{

Is not the correct way to create your main function. The correct way is:

int main()
{
    //code here
}

or

int main(int argc, char *argv[])//or char **argv or char argv[][]
{
    //code here
}

2) Use appropriate data structures.

This will make your code a lot easier to use and read and debug. Instead of having GPA,ID,etc just lying out in the open, you should wrap them up in a nice package, like so:

struct Student //a class would be better, but I feel like you probably haven't learnt about classes yet, no?
{
    string id;
    string year;
    float gpa;
};

3) Use Modularization.

This means breaking your code up into managable bites. What you did (shoving everything into main) is like trying to eat a sandwich in one big bite. Your are going to choke, break it into smaller chunks!

In this case you should create a bunch of helper functions to break up the task into managable segments, like so:

//load a student from the file
Student loadStudent(fstream file)
{
    Student ret;
    file>>ret.id>>ret.year>>ret.gpa;
    return ret;
}

4) Use arrays

I understand if you do not know about dynamic memory allocation yet, but this problem is easiest if you just use a buffer to store your student gpa's so you can calculate the average. …

iamthwee commented: loved the sandwich analogy +14
Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

Looking at the standard streams provided by the stl libraries, it seems as though it is impossible to have 1 stream to use for both standard console IO and file/string IO. However, before I give up I would like to ask, is this possible:

generic_stream stream;
stream=cin;
//now I can use stream as cin
stream>>value;
stream=fstream("myFile.txt");
//now stream acts as a stream to myFile...
value>>stream;
stream=sstream("123 test");

From what it looks like, since fstreams use input and output they derive iostream, which in turn derives istream, which in turn derives ios. However cout uses ostream instead of istream and therefore its common ancestor with fstreams would be ios. But it doesn't look like ios has any actual IO functionality. Does this mean I am SOL? If there is no way using the STLs is it maybe possible using the old c libraries (can a FILE point to standard console IO)?

Labdabeta 182 Posting Pro in Training Featured Poster

There are a few issues with your code, however the one causing the issue is a simple OBOE (off-by-one-error). The number one thing that jumps out at me is that you really should be using an array here, it will literally make the part of the code that deals with word## 10 times smaller!

In case you are not familiar with arrays, they are (for the purposes of this discussion) a way to make a large number of variables that you can index with a number. You declare them with square brackets.

Another thing that will make your code easier to read (and thus easier to fix) would be to modulize more. Each function should do a simple task, so having one function that does multiple tasks makes it hard to read.

In the end, the WordCharacter function should end up looking like this:

//this function does the job of removing punctuation from a string
string removePunctuation(string input)
{
    string temp = input;
    int punct = 0;
    int length = temp.length();
    for (int x = 0; x < length; x++)
    {
        if (ispunct(temp.at(x)))
            punct++;
    }
    int x1 = 0;
      for (int x = 0; x < length; x++)
    {
        if (!ispunct(temp.at(x)))
            temp.at(x1++) = temp.at(x);
    }
    return temp;
}

//deal with number in main() only deal with printing the number of words of each length here
void printWordCharacter(string &input)
{
    int word[10];//declare 10 ints called word[0], word[1], etc... (note that they start at 0, not 1)
    string newString;//newString is a …
Labdabeta 182 Posting Pro in Training Featured Poster

You have 1 syntax problem and a few redundancy problems. First lets tackle the syntax problem so that you can get your code to run.

The syntax error is that void distance(miles) is not valid C++ code. When you have parameters in a function it must have a type. What you want is void distance(double miles) which is exactly what you wrote in the class description.

This leads to the next issue, namely that you are going to end up asknig the user for the miles variable twice. Instead you want to pass miles into the function, like vmanes said. Thus your fixed distance function is:

void distance(double miles) {
    fuelLevel-=miles/mpg;
}

Finally, there is a redundancy in your constructor. While it works fine, it is very silly. Here is your constructor:

Car::Car(double mpg, double capacity): mpg(mpg), fuel_capacity(capacity){
mpg = mpg;
fuel_capacity = capacity;
fuelLevel = 0.0;
}

Which is essentially the same as:

Car::Car(double mpg, double capacity): mpg(mpg), fuel_capacity(capacity){
//:mpg(mpg) becomes:
mpg = mpg;
//:fuel_capacity(capacity) becames:
fuel_capacity = capacity;
//now the next two lines are redundant:
mpg = mpg;
fuel_capacity = capacity;
fuelLevel = 0.0;
}

A better constructor is:

Car::Car(double mpg, double capacity):  mpg(mpg), 
                                        fuel_capacity(capacity),
                                        fuelLevel(0.0)//you can set these to values too
                                        {/*no function body at all!*/}

Hope this helps!

Labdabeta 182 Posting Pro in Training Featured Poster

I am not 100% sure what you are asking since I can't access the code. However I think I understand what you are asking. You have two classes that refer to each other and want to have each in their own headers. The key to remember is that the #include "fileName.h" line acts identically to a copy-paste of the contents of fileName.h into your file, turning your entire program into one big file (see http://en.cppreference.com/w/cpp/language/translation_phases).

To have two classes refer to each other in one file this is how you do it:

#include <iostream>
class A; //forward declaration of class A
class B; //forward declaration of class B
class A
{
    B *b;
    public:
    A():b(NULL){}
    A(B *b):b(b){}
    A &set(B *b){this->b=b;return *this;}
    A &print(){std::cout<<"A"<<std::endl;return *this;}
    B *get(){return b;}
};
class B
{
    A *a;
    public:
    B():a(NULL){}
    B(A *a):a(a){}
    B &set(A *a){this->a=a;return *this;}
    B &print(){std::cout<<"B"<<std::endl;return *this;}
    A *get(){return a;}
};
int main()
{
    A a;
    B b(&a);
    a.set(&b);
    a.print();
    b.print();
    a.get()->print();
    b.get()->print();
    return 0;
}

Which works as expected, printing ABBA across four lines. Now when we make our header files we want to ensure that including them generates the same code. As such we link the class files with a header file that contains the forward declarations, like so:

AB.h:

#ifndef AB_H
#define AB_H

#include <iostream>

class A;//forward declaration
class B;//forward declaration

#include "A.h"
#include "B.h"

#endif //AB_H

A.h:

#ifndef A_H
#define A_H

class A
{
    B *b;
    public:
    A():b(NULL){}
    A(B *b):b(b){}
    A &set(B …
Labdabeta 182 Posting Pro in Training Featured Poster

I am not sure exactly what you mean by #2, but I can tell you about #1. The difference is that, as far as I know, you cannot create an array variable without setting it to point to a value. Specifically when you say int a[5]={1,2,3,4,5}; it sets a to point to the address where the 1 is stored, while ensuring that 2,3,4,5 are in the following address spaces. If you were to then move where a points you would have an issue because you would lose access to your original array (and I am not sure if C would clean it up for you). However, in the context of function parameters arrays and pointers can be used almost interchangeably. For example:

void arrayTest(int a[])
{
    a[0]=7;
}

Is the same as:

void pointerTest(int *a)
{
    *a=7;
}

Just like:

int arrayAccess(int a[])
{
    return a[7];
}

Is the same as:

int pointerAccess(int *a)
{
    return *(a+7);
}

And of course a[7] and *(a+7) can be interchanged.

So the reason we declare pointers seperately is two-fold:

1) It doesn't automatically create the object we wish to point to.
2) It describes what the variable is, making code more legible.

Labdabeta 182 Posting Pro in Training Featured Poster

Step 1: Install Compiler/IDE (I like to use Code::Blocks/G++)
Step 2: Write program (You can learn C++ from many sites, I taught myself using learncpp.com)
Step 3: Compile program (I set up Code::Blocks to use g++, but using the built-in MinGW works too)

My guess is that you have either been skipping class, or not paying attention during it, and now an assignment is due and you want strangers on the internet to do your assignment for you. If that is the case you have come to the wrong site. However if you need help fixing your code or IDE or compiler, that is where we can help. We will not do your work for you, but we are happy to help you once you have made a genuine effort.

Labdabeta 182 Posting Pro in Training Featured Poster

Basically, when a function is called in assembly language (which is what your C++ code gets turned into by the compiler) it actually takes real time to set up the function and return from it. In pseudocode this is what a function actually is (C++ hides this from you):

  1. Save all temporary variables that you use (Assembly has a finite number of temporary registers, if you want to use one you have to save its state)
  2. Load the arguments of the function into some of those temporary variables.
  3. Use those variables somehow.
  4. Save the result in a special temporary variable (or to memory)
  5. Load all the same registers again.
  6. Return from the program.

So you can imagine that this:

int add(int a, int b)
{
    return a+b;
}
//...
int c;
c=add(1,2);

Becomes something more like this in assembly (obviously the code shown is not a real assembly language):

add://its a label, thats what assembly uses a lot of, please don't use them often in C++
    //this 'function' assumes that r0 (one of the temp registers) contains a
    //  and that r1 (another register) contains b already!
    push r2 //if we want to use r2 (yet another register) we need to save its state on the stack
    r2=r0+r1 //or more likely add r2,r0,r1, but the point is to store the value in r2
    //now lets assume we 'return' the value by storing it back into r0
    r0=r2
    pop r2 //reset the value of the register we …
Labdabeta 182 Posting Pro in Training Featured Poster

The issue is that char is an integer type, so a+b will add the ASCII values of a and b, which gives weird output. Converting them to strings works fine, except that strcat uses char* c-style strings and you used std::string c++ style strings.

Here you have 2 options:

Option A: C-Style strings

char result[3];//a,b,NULL
result[0]=a;
result[1]=b;
result[2]=0;//null terminate

cout<<result<<endl;

Option B: C++-Style strings

string c=(string)a;
string d=(string)b;

cout<<c+d<<endl;

For obvious reasons the C++ style is usually considered better. However the c-style version likely takes less memory. Both should work though.

Hope this helps!

Labdabeta 182 Posting Pro in Training Featured Poster

There are a few problems with your code, but the only critical errors are in the calculate function so I will start there.

First of all when you declare temp and x you dont give them values, so they can be any value they want. This means that when you say:

temp = temp - (pow(ang, i+1)/factorial(i));

The result could, technically, be anything!

Secondly your implementation is extremely redundant. Trace the i in your for loop and you will see that it is always odd, so only one of your if statements will ever execute. Not to mention the fact that you could have merely used an else statement to write the second if.

Finally there is the overall logical error. The pseudo-code for computing cosines is as follows:

Option 1: Count by 2s, store (-1)^n
1. Set the total sum to 0.
2. Set the subtract flag to false. (We add the first term)
3. Set the counter, i, to 0. (This is your for loop)
4. Set temp to the current term: temp=x^i/i!
5. If the subtract flag is true negate temp.
6. Invert the subtract flag
7. Add temp to the sum.
8. Add 2 to i
9. Go to 3

Option 2: Count by 1s, calculate 2n
1. Set the total sum to 0.
2. Set the counter, i, to 0. (This is your for loop)
3. Add (-1^i)x^2i/2i! to the sum.

mike_2000_17 commented: Nice and thorough! +14
Labdabeta 182 Posting Pro in Training Featured Poster

This is a classic problem in computer science. Basically it is a neat case of induction.

For towers named A,B,C:
Start with a tower of just 1 disk. Transferring it is as easy as moving it from A->C.

If you have more than 1 disk its a bit more complicated. Start my moving all but 1 disk to the extra peg. How? By following these same instructions! Next move the biggest disk onto the final peg. Next move all the other disks from the extra peg to the final peg. This can also be done by following the same steps. Now you are done!

The key is that you change which peg is the initial, final, and extra peg, then keep recursively moving smaller towers until all you need to do is move towers of 1 disk, which is easy!

This is exactly what your code does.

1 disk: if only 1 disk, then move it.

if (d==1)
{
    cout<<"\nShift top disk from tower"<<tower1<<"to tower"<<tower2;
    return;
}

n+1 disks:
Step 1: move n disks to extra tower (tower3), while doing this the final tower (tower2) acts as the extra tower.

TOH(d-1,tower1,tower3,tower2); //TOH(n,initial,final,extra)

Step 2: move 1 disk to final tower (tower2)

cout<<"\nShift top disk from tower"<<tower1<<"to tower"<<tower2;

Step 3: move n disks from the extra tower (tower3) to the final tower (tower2) using the initial tower (tower1) as the extra.

TOH(d-1,tower3,tower2,tower1);

So for d=3 you have: (using A,B,C as the …

ddanbe commented: For the effort :) +15
Labdabeta 182 Posting Pro in Training Featured Poster

You cannot change a function's behaviour on an object, only on a class. To get the exact functionality you showed you would have to use a function pointer as a member of the test class:

class test
{// private:
    public:
    event<>(*Printed)();
    test()
    {
        Printed=[]{;}//I have yet to take a good look at the syntax for this
    }
};
test a;
a.Printed=[]{cout<<"\nMessage Printed\n";}

However this is not what people are usually referring to when they use polymorphism. Polymorphism is almost always used to represent the "is a" relationship where something changes. For example a square "is a" rectangle so this is proper practice for a square and rectangle class:

class Rectangle
{// private:
    int width,height;
    public:
    virtual int getArea(){return width*height;}
};
//time for polymorphism (technically here it is just inheritance)
class Square:public Rectangle
{// private:
    public:
    virtual int getArea(){return width*width;}
};

Because of the virtual label the following code would execute the following functions:

Rectangle r;
Square s;
Rectangle *rp;
Rectangle *rps=&s;//valid!
//Here width*height is called, as you would expect
r.getArea();
//Here width*width is called, as you would expect
s.getArea();
//Here, you still get width*height
rp->getArea();
//Here, since getArea was virtual, you get width*width
rps->getArea();

So basically to override a function in a new CLASS it is as easy as writing a new version of the function (virtual keyword is optional unless you deal with pointers to base classes). However overriding a function in a new OBJECT is very difficult.

cambalinho commented: thanks for try +2
Labdabeta 182 Posting Pro in Training Featured Poster

It is completely situational. Here is an example:
1000001

What is that number?
If you interpret it as a 7-bit unsigned number you get 65.
If you interpret it as a 7-bit sign/magnitude number you get -1.
If you interpret it as 1's complement you get -63.
If you interpret it as 2's complement you get -64.
If you interpret it as 8-bit 2's complement (very common) you get 65.
If you interpret it as an ASCII character you get 'A'.
If you interpret it as BCD (binary coded decimal) you get 41.

Basically you can represent anything which is countable using only 1s and 0s, and similarly every set of 1s and 0s can represent any number of things. The only way to know which interpretation to use is by situation.

In any given assembly language they will usually tell you exactly what things mean. Incidentally, once you assemble your code in assembly it will be turned into another number. For example in MIPS assembly (as described by my professor) you have:

add $1,$2,$3 = 0000 0000 0100 0011 0000 1000 0010 0000

The key is that n bits can represent 2^n possible 'thing's you need to define what 'thing' you want them to represent. In the case of 1s or 2s complement you just look at the first bit, if it is 1 the number is negative:

1011 in 4 bit 2's complement = -5
1011 in 8 bit …

ddanbe commented: Good advice. +15
Rahul47 commented: That was helpful. . . thankx +3
Labdabeta 182 Posting Pro in Training Featured Poster

I believe the true answer is irrelevant. Firstly it could differ based on implementation, and it is entirely possible that if it currently does have a limit, it would be removed in future. The big issue is that whether or not you have space for something is irrelevant.

There are certain numbers that are just so incredibly massive that they are assumed to be impossible to compute (http://en.wikipedia.org/wiki/Transcomputational_problem).

As it turns out 50! is not really all that big (relatively speaking) coming in at only 65 decimal digits. As such I would not be surprised if BigInteger COULD calculate it.

The thing is that if you start pushing the envelope of how big a number you can calculate you run into the wall of time and space. The algorithms will take time to run and there wont be enough space to run them. This is where the definition of a transcomputational problem comes in. A transcomputational problem is one which would take a computer the size of the earth longer than the age of the earth to compute. Obviously BigInteger frankly will be unable to deal with this, and even if it could it wouldn't matter since you could never get the output you need from it.

Luckily there are some clevel argorithms to keep big number use in check, often relying heavily on modular arithmetic (http://en.wikipedia.org/wiki/RSA_%28algorithm%29). If you really want to have fun with big numbers you will likely have to find a way to …

Labdabeta 182 Posting Pro in Training Featured Poster

Perhaps see how many of these you may wish to include: http://en.wikipedia.org/wiki/List_of_mathematical_functions

Other than that, if you finish early and want an extra challenge you can modify your program to be "arbitrary" precision. IE: with integers/rationals infinite precision and with irrational numbers some set, very high, precision.

Finally, I agree that UI should be the last thing you do. If you use proper OOP it shouldn't be an issue.

iamthwee commented: well said +14
Labdabeta 182 Posting Pro in Training Featured Poster

In my programs I usually only encounter 3 types of epic one liners, they all use the ternary conditional operator extensively.
(all in c++)

Type 1: Conditional arithmetic - When I want to change how an equation behaves based on conditions. Example taken directly from the add function of my integer library: (i<s?v[i]:0)+(i<o.s?o.v[i]:0)+(carry?1:0).

Type 2: Inline switch statements - Any switch statement can be made inline with the ternary operator.

switch (x)
{
    case A:doA();break;
    case B:doB();break;
    case C:doC();break;
    default:doD();break;
}

becomes:

(x==A?doA():(x==B?doB():(x==C?doC():doD())));

Type 3: Complicated bitshifty stuff, typically to create inline hash functions. I can't think of a good example off hand, but they end up looking really cool.

However, I believe epic one liners are generally considered bad practice. That is why I try to keep a comment above each one that describes what the one-liner does.

Labdabeta 182 Posting Pro in Training Featured Poster

I was actually thinking of a more straightforward approach. Read the whole block into a string (so the string contains, for example, "12:30"). Then remove the punctuation (so "12:30" becomes "1230") then use atoi() or atol() or stringstream() to convert it to your integers. The benefit of this method is that you will not have to shift the numbers at all, and all of your dates/times should be whitespace seperated, which lends itself nicely to fstream or stringstream >> operators. Removing characters from a string is fairly simple:

//don't quote me on this, it is from memory
void removeFromString(std::string &str, char ch)//removes all occurances of ch in str
{
    int index;
    while ((index=str.find_first_of(ch))!=std::string::npos)
        str.erase(index,index+1);
}
Labdabeta 182 Posting Pro in Training Featured Poster

@rubberman I have looked at them, and none of them have allocation for transcomputable numbers. This is obviously because there is no reason to use them. However for this competition transcomputable numbers are fair game. All we care about is the theoretical computability. So even if it would take a computer the size of the earth and more than the lifespan of the earth to calculate a number, our programs shall still do it!

Anyways, by modifying how my files work to a more iterative style (instead of having files of files I just have a string of files, similarly to a linked list) I have been able to rewrite my recursive functions iteratively. So all is well.

rubberman commented: Neat! Hope you win... :-) +12
Labdabeta 182 Posting Pro in Training Featured Poster

Before getting to the issue at hand, I need to mention that you are making your code a little harder to read because you have double x; and double value; as both global and local variables. Please move those into the main function, they have no place in the global namespace. In fact that could be part of your problem, your compiler (if it isn't standard) could be using those x/value rather than the ones in your sine function. Also instead of using a while loop this is the perfect place for a for loop: for (int count=3; count<=100; count+=2) will be a lot easier than the while loop. Also you really should put 100 into a constant global of some kind at the top of your program. I would suggest #define PRECISION_ITERATIONS 100 then use for (int count=3; count<=PRECISION_ITERATIONS; count+=1) that way if you ever have to change the precision from 100 to something else you won't have to search through your code, instead you just go to the top and change its value. (You could also ask the user to enter the number of iterations)

Now onto the formula. It looks like you just plugged in the formula given without understanding it. What your teacher is trying to get you to do is approximate sin/cos using a Maclaurin series. If you do not know what that means then I don't blame you. It often is not taught until 1st year university (thats when I was taught it). However …

Ancient Dragon commented: great :) +14
rubberman commented: To mis-quote AD, most excellent post! :-) +12
Labdabeta 182 Posting Pro in Training Featured Poster

Firstly, this is more of a code snippet than a discussion thread, no? Secondly the methodology you used is flawed. Instead of getting input inside the class functions you should move it outside. Instead of enqueue() you should use enqueue(int val) so that you can add values to the queue however you want. This is very important because lets say for example you have to get your values from a file. To use your code you would have to redirect cin to that file, and probably cout to a file too to keep messages from popping up. However if you use proper modularization this is not an issue. Always try to create classes that act as generally as possible so that they can be reused repeatedly. For example a queue should ONLY be a queue, not a queue and an input parser! As such I would suggest the following improvements:

A) Use standard names. For queues typically the functions are called enter and leave (enter adds an element to the queue, leave removes one and returns it).
B) Allow for input to the enter function so that all it does is store things.
C) If you are comfortable with them, this is the perfect chance to use a template parameter so that instead of being an integer queue, your queue class is just a queue.
D) Remove the using namespace std; line, it means that anybody using your code also has to use the std namespace, which …

Labdabeta 182 Posting Pro in Training Featured Poster

I think the easiest way to understand is to understand where Constructors and Destructors come from. Back in the days of C you did not have classes, only structs. As such you had to write a function that would create your struct (and usually return a pointer to it) as such you can think of Constructors and Destructors as functions that the compiler automatically inserts. Here is an example:

class TestClass;
//We are going to pretend that TestClass's constructor is actually this: (its not too far from the truth)
TestClass TestClassConstructor();
//and that this is its destructor:
void TestClassDestructor(TestClass tc);
//The compiler is going to replace this line:
TestClass myTestObject;
//with this one:
TestClass myTestObject=TestClassConstructor();
//and when it goes out of scope like in this example:
{
    TestClass test;
}
//the compiler will have to call the destructor
{
    TestClass test=TestClassConstructor();
    //out of scope time, must destruct!
    TestClassDEstructor(test);
}

You can see how since the compiler automatically tries to call the constructor and destructor in a very public way it runs into issues if the constructor or destructor are private. This allows you to do some interesting things. Lets say that you have a class to hold a fraction and you only want to allow people to make it with a constructor that specifies its numerator and denominator. You could do it this way:

class Fraction
{// private:
    int numerator,denominator;
    //Since this constructor is private it cannot be used outside the class
    Fraction();
    public:
    Fraction(int num, int …
Labdabeta 182 Posting Pro in Training Featured Poster

I think you are still getting the errors because you are still trying to use polymorphism. If you use the const AbstractType & (inheritance) technique then you don't even need the <DefinedClass> at all. Also you don't need a pointer! Just this is how you use it:

DefinedClass dc=new DefinedClass;
new FileWritter("filename.file",dc);//it gets referenced automatically!

Also it seems as though in your definition of FileWritter (in FileWriter.h) you didnt define the functions you are trying to use. So here is a translation of your errors:

C4430: You didnt provide a type inside the <> section of your class... we're gonna assume you want ints. (fix this by just not using templates... they aren't correct here!)

C2143: Since it is still waiting on the <> section it gets confused when you throw in an & sign. Same fix as before.

C2509: What are you trying to pull? You didn't tell us you were making a constructor for FileWritter. You can't make an outside of class definition of something not already in the class. Example:

class Test
{
    public:
    void myFunctionA();
};

//This works, because the compiler knows that there is a myFunctionA inside Test
void Test::myFunctionA()
{
    //dosomething
}

//This doesn't work, because the compiler wasn't told in advance that this would be here!
void Test::myFunctionB()
{
    //dosomething
}

C2955: Again... when are you going to give us the <>... we have no idea what we are dealing with!

C2509: Again... you never told us you were …

Labdabeta 182 Posting Pro in Training Featured Poster

What you are asking about is called "type erasure" it is basically the combination of templating and inheriting. Unfortunately C++ does not support type erasure (as far as I know). As such you have to choose between templates and inheritance. Here is an example of each solution:

Inheritance based:

class AbstractClass
{// private:
string exampleData;
public:
AbstractClass();
virtual string getData()const{return exampleData;}
virtual void setData(string &o){exampleData=o;}
};

ostream &operator<<(ostream &left,const AbstractClass &right)//this should work for any class that inherits from AbstractClass
{
    left<<right.getData();
}

class FileWriter//there is only one 'T' in writer
{// private:
    ostream file;
    public:
    FileWriter(string fileName, const AbstractClass &ab){//MUST BE A REFERENCE OR POINTER!
        file.open(fileName.c_str());
        file<<ab;
    }
    ~FileWriter(){
        file.close();
    }
};

And here is the template based solution:

template <class AbstractClass>
class FileWriter
{// private:
    ostream file;
    public:
    FileWriter(string fileName, const AbstractClass &ab){//Abstract class must implement ostream&<<AbstractClass&
        file.open(fileName.c_str());
        file<<ab;
    }
    ~FileWriter(){
        file.close();
    }
};

Here are example uses of each:

Inheritance method:

class myClass:public AbstractClass
{};//normally this would have something in it. And it can modify get/setData to change its output behaviour
myClass mc;
FileWriter fw("myFile.txt",mc);

Template method:

class myClass
{};//normally this would have something in it. And it can modify the following function to change its output behaviour
ostream &operator>>(ostream &left, myClass &right)
{
    left<<"This is a myClass";//for example
}
myClass mc;
FileWriter fw("myFile.txt",mc);
Labdabeta 182 Posting Pro in Training Featured Poster

Im fairly certain that the language you are using is objective-c. You will most likely get more luck if you move this over to the objective-c section.

Labdabeta 182 Posting Pro in Training Featured Poster

Firstly, to clean up your code you should use a multidimensional array... I assume you know that arrays are basically a way to prevent you from doing this (at least statically allocated ones):

int var1;
int var2;
int var3;

Instead they allow you to cobine those variables into:

int var[3];

Now look at your code. This is a section of it:

double exam1[NUMBEROFSUDENTS];
double exam2[NUMBEROFSUDENTS];
double exam3[NUMBEROFSUDENTS];
double exam4[NUMBEROFSUDENTS];
double exam5[NUMBEROFSUDENTS];

Look familiar? The solution to this is to make an array of arrays:

double exam[NUMBEROFSTUDENTS][5];

That solves your problem with the uglyness of your code. Now onto the problem of it not being right. I feel like you are not fully understanding how classes work. The whole point to a class is so that you don't have to send it all those arguments for all of its functions. Instead you can store them inside the class and then the compiler basically passes them for you! This means that this whole section is just wrong:

class student
{
public:
void setGrades(int studentId[], double exam1[], double exam2[], double exam3[], double exam4[], double exam5[], int count);
int getGrades(int studentId[], double exam1[], double exam2[], double exam3[], double exam4[], double exam5[]);
void error(int studentId[], double exam1[], double exam2[], double exam3[], double exam4[], double exam5[], int count);
void average(int studentId[], double exam1[], double exam2[], double exam3[], double exam4[], double exam5[],
double total[], int count);
void newAverage(double exam1[], double exam2[], double exam3[], double exam4[], double exam5[], int …
Labdabeta 182 Posting Pro in Training Featured Poster

Your issue is with integer conversion. Lets say, for example that you send the array that you showed, and say 4 for totals. At values[0][0] the result is 3 right? So you can pretend to swap in a 3 there... and swap in 4 for totals. What does 3/4 become in c++ (NOTE: integer division!). The answer is 0. That is why its all writing 0s. If you want the original array then don't divide by totals, if you want the fractional value then try (double)values[count][count2]/totals so as to call floating point arithmetic.

Labdabeta 182 Posting Pro in Training Featured Poster

Your syntactical error is that max goes out of scope, but you have many more errors that are logical. For instance that for loop will run through and gather all the data into the array. Afterwards i will be 100... so you will only be using the very last thing entered. I am not sure how you would want to fix this. I would put the input into the do-while loop and forget about the for loop completely. Here is your code with the errors highlighted by comment:

    #include <iostream>
    #include <math.h>
    #include <cmath>
    #include <climits>//for INT_MIN, INT_MAX
    using namespace std;
    int main ()
    {
    float sum = 0.0;
    float sub = 0.0;
    float variance = 0.0;
    float mult = 1.0;
    float mean = 0.0;
    float min=INT_MAX,max=INT_MIN;//create min and max here
    int i;//remove this and change all the i's to n's
    float arrayVal[100];
    int n=0;
    cout<<"input your values"<<endl;
    do
    {//note the removed for loop.
    cin>>arrayVal[i];
    sum += arrayVal[i];
    if (n == 0)
    {
    sub = arrayVal[i];
    }
    else
    {
    sub-=arrayVal[i];
    }
    mult *= arrayVal[i];
    //do not recreate max
    if (max>= arrayVal[i])
    {
    max=arrayVal[i];
    }
    //do not recreate min
    if (min <= arrayVal[i])
    {
    min=arrayVal[i];
    }
    n++; // n represents the number of values input by the user
    }
    while (i<100 && arrayVal[i]!=0);
    mean = sum/n;
    for (i=0;i<100;i++)
    {
    variance += pow((arrayVal[i]-mean),2);//using pow for squaring is sorta lame... (arrayVal[i]-mean)*(arrayVal[i]-mean) is arguably better
    }
    float standDev = sqrt(variance);
    cout<<"Sum = "<<sum<<endl;
    cout<<"Sub = "<<sub<<endl;
    cout<<"Mult = "<<mult<<endl;
    cout<<"Max = "<<max<<endl; …
Labdabeta 182 Posting Pro in Training Featured Poster

Veni, Vidi, Vici (I came, I saw, I conquered) - Julius Caesar
Veni, Vidi, Didici (I came, I saw, I learnt) - Me :)

cproger commented: lol :) +0
Labdabeta 182 Posting Pro in Training Featured Poster

"The natural man has only two primal passions, to get and to beget." - Sir William Osler (Incidentally an alumni of my high school!)

Labdabeta 182 Posting Pro in Training Featured Poster

"I'd hate to die twice. Its so boring." - Richard Feynman's dying words.

Labdabeta 182 Posting Pro in Training Featured Poster

Both of my parents are doctors... here are some tips that work wonders:

1) STAY HYDRATED!!!
2) Try leaning your head to the left, then right. Make your head look like this \/\/\/... do it slowly-ish. This causes your jugular veins to get compressed. The brain, fearing that something is compressing them, takes a large amount of blood in to compensate. This leads to it becoming temporarily more awake.
3) Buy a false sunlight. Especially if you live in extreme latitudes (like me) you can trick your body into thinking it is daytime by shining a bright light that simulates sunlight onto you (not just your eyes, your skin too). If you live in dark countries normally, you should do this during the day as well. Also most of these lights have alarm clocks built in... I know from exprience, it is hard to sleep through a false sunlight shining on your face! (Ill provide a link to one if required)
4) Excersize (I can never spell it right)
5) Stay away from caffeine. First of all caffeine only works if you are well hydrated, if you are dehydrated it will make you tired. Secondly caffeine messes with your circadian rhythms, making you far more likely to be tired at unusual times. Finally caffeine only works for a short while, afterwards you would need more to keep you awake.
6) Get onto a solid circadian rhythm (sleep cycle). Basically set aside a specific time where …

Labdabeta 182 Posting Pro in Training Featured Poster

I got 22... but that was with a 0 in the relationship questions, but I have never really been in any serious relationships and I am pretty sure that I would eek a few more points out of those. Also I have been diagnosed with ADHD,OCD, and Aspberger's syndrome... so the test is likely fairly inaccurate for me. I have also been through a lot of psychological testing, so I am pretty sure that if I were a psychopath, one of the psychiatrists would have noticed. :)

Labdabeta 182 Posting Pro in Training Featured Poster

The issue is on line 26. You check if the sign isnt + OR isnt - OR isnt etc.. you want ANDs there. :)

Labdabeta 182 Posting Pro in Training Featured Poster

Here is what I have to say. I used a mac all throughout my childhood, then got a windows computer for school and got used to it. Then when I got really into programming I put a linux partition on my laptop. So I have experience with most OSs and I try to have an unbiased view (even though personally I hate crapples). So here we go... Pro/Con list and ideal users:

Apple OSs: Computer N00bs with money

The good thing about apple computers is that, while saying that they are the most user-friendly is quite an exageration, they tend to need very little maintanance. When they do need maintenance apple stores will be able to help, although it can be very hard to find one near you. On top of that Apple OSs tend to come with a lot of default software and easy to get apps. These programs are not as well designed as more expensive ones, but because they give easy access to some basic computer skills novice computer users are capable of doing near-professional grade work. The two biggest downsides I have found are cost and efficiency. Apples are waaay overpriced. As far as I am concerned there is really no argument there... about a year ago I looked at the price for an apple laptop and found that for just the price of the hard drive upgrade I could create the upgraded version with a slightly larger form-factor. The only difference would be size/weight/lack of …

Labdabeta 182 Posting Pro in Training Featured Poster

Hello. I was reading http://xkcd.com/287/ while bored and thus decided to write a program that would solve such np complete problems. Here is what I got:

#include <iostream>
#include <vector>
using namespace std;
template <typename T>
T NPMenuProblem(T desired, vector<T> options, vector<T> &ret)
{
    vector<T> save=ret;
    T remainder;
    T min=desired;
    vector<T> minsol;
    for (int i=0; i<options.size(); ++i)
    {
        ret=save;
        if (desired-options[i]>0.0)
        {
            ret.push_back(options[i]);
            remainder=NPMenuProblem(desired-options[i],options,ret);
            if (remainder==0)
                return 0;
            else if (remainder<min)
            {
                minsol=ret;
                min=remainder;
            }
        }
    }
    ret=minsol;
    return min;
}
int main()
{
    vector<int> opts;
    opts.push_back(215);
    opts.push_back(275);
    opts.push_back(335);
    opts.push_back(355);
    opts.push_back(420);
    opts.push_back(580);
    vector<int> ret;
    int des=1505;
    int rem=NPMenuProblem(des,opts,ret);
    for (int i=0; i<ret.size(); ++i)
        cout<<ret[i]<<" + ";
    cout<<" = "<<des<<" - "<<rem<<endl;
    return 0;
}

The issue is that it doesn't work and I cannot figure out why... any advice?

Labdabeta 182 Posting Pro in Training Featured Poster

Basically, a linked list for a stack will only have one link, pointing to the next element. As such your stack will look something like this:

First->Second->Third->NULL (where -> indicates that the value has a pointer to the value to the right)

In terms of the "standard" linked list struct:

struct LinkedListNode
{
    string val;//this doesnt have to be a string, it can be literally anything!
    LinkedListNode *next;//this is the key to linked lists
};

With the above structure the example would look like this:

Your stack object would be First and would contain "First" and a pointer to Second, which would contain "Second" and a pointer to Third, which would contain "Third" and a pointer to NULL.

The key to linked list implementations is that when you add a node you can't do it like this:

void addNode(LinkedListNode *myStack)//this is an epic hint!!!
{
    LinkedListNode newNode={"New",myStack};
    myStack=&newNode;
}

The reason is that newNode will go out of scope. The answer is to use the new operator. IE:

LinkedListNode *newNode=new LinkedListNode;//ta-da!

The new operator makes the new structure "global" (in a way). Other than that a stack is actually pretty easy to implement. If you are stuck on a particular function I would suggest a diagram. Draw each node as a box. In each box put all the values that a node should store, then draw an arrow from the box to whatever its "next" pointer points to. Then using just this diagram implement …

Labdabeta 182 Posting Pro in Training Featured Poster

The issue is that reverselist as you wrote it expects a reference to a pointer of a nodetype, but you passed it num#.head_ptr which is of type pointer which will be converted to a const reference to a pointer of a nodetype (since num1,num2 are declared const in the function definition). Basically you either need to edit reverselist so that it takes const references (I doubt that will work at all!) or you can edit the binary + operator so that it takes binary references (minus the const).

Labdabeta 182 Posting Pro in Training Featured Poster

Yeah, the problem is that ^ is not the exponent operator in c++. Rather a^b performs the bit xor operator on the two operands. As the bit xor operator requires two integer types to work (or even to make decent sense) it makes no sense to have it work on floats. Instead you have to find another way to implement exponents. (phorce gave the simplest solution to the ^2 problem, ie a*a)

Labdabeta 182 Posting Pro in Training Featured Poster

How do you intend to compare a string to a single character? An overloaded operator does not seem valid there. Perhaps create some kind of areEqual function instead. My guess is that you have made a logic error in that you are trying to compare two variables of different types (very different types).

111100/11000 commented: I changed from "string plaintext" to "char plaintext" and it works.Thnx +0
Labdabeta 182 Posting Pro in Training Featured Poster

I will help you out with what I can see from a quick glance. #1: Your vector stores generic 'Type' variables, so unless all of your vectors are vector<int> then you need your push_back function to take a Type value. Also you make a critical error that I used to make all the time with dynamic memory allocation. Here is how to do it properly:

Type *tempArray=new Type[arraySize];
for (size_t i=0; i<arraySize; ++i)
    tempArray[i]=sourceArray[i];//up until here we did the same thing
tempArray[arraySize++]=newValue;//this is pretty simple, you increase the array size, but return the old size to the [] operator, basically appending the value AND updating the size variable.
delete[]sourceArray;//we don't need it anymore
//here you re-allocated sourceArray and copied tempArray to it. You do not have to do it
sourceArray=tempArray;//now since the pointers are equal sourceArray will contain the contents tempArray.

You would think that since tempArray is about to go out of scope sourceArray will be invalid... you would be right if it was sourceArray=&tempArray because it is true tempArray will be deleted. The thing is that tempArray stores 1 int, corresponding to the location in memory of the array. That int is also in sourceArray. As such it still holds the same data as before!

Labdabeta 182 Posting Pro in Training Featured Poster

Here is the issue, at least what I understand of it based on a preliminary review of your code. Basically, in the handle_input function, you declare a new event, but you do not set it to anything. It is going to be filled with whatever is left on the stack, or 0 depending on your compiler. What you need to do is somehow send it the same event object that recieved the call to SDLPollEvents. Judging by your style of code, I would suggest making a global sdl event.

While I am on your style of code, I feel inclined to tell you that your extensive use of globals is not generally considered good practice. Instead of a bunch of globals, maybe create a control object like this:

class Control
{
    private:
    //your globals here
    int exampleInt;
    SDL_Event exampleEvent;
    public:
    Control();//here you could set up SDL?
    ~Control();//here you could clean up your mess (close SDL, free surfaces, delete memory, whatever)
    int getInt(){return exampleInt;}
    void setInt(int val){exampleInt=val;}
    SDL_Event getEvent(){return exampleEvent;}
    void pollEvent(){SDL_PollEvent(&exampleEvent);}
};

Hope this helps!

claywin commented: Thanks! This was very helpful! +0