StuXYZ 731 Practically a Master Poster

First off the most scary thing that I see is the global variables defined just below your line using namespace std;. Arrrhh.... don't do this, they are not needed.

Next reduction is missing a few brackets.

Yes gcd CAN be zero if say numerator and denominator are 1.

Now the algorithm used is a mess. It is easier to count up, than down.
You will not found a common factor that is bigger than the SMALLEST of the
numerator and denominator, e.g. 1/387642212 is not going to be reduced
regardless of the factors in the denominator.

So the algorithm you need:

Loop I: from 2 to smallest number
    while (I is common factor)
        divided denominator and numerator
    recalc smallest number

Note: It is very important to check a factor many times, e.g. consider 16/32,
2 is a factor but you can divide by 2, four times.

Improvements of this algorithm include : using a prime sieve, so you only have
to test primes, stepping up in 2s, looping to the sqrt(smallest) , but remembering
to test the smallest number as well.

StuXYZ 731 Practically a Master Poster

I believe that sfuo is correct that the problem is you lack of cast to a double

The reason that you had the original problem was that 5/9 is integer/integer. In
integer arithmetic you don't change type and an integer is returned: e.g 5/9 is
zero. Additionally 8/9 is zero, and 11/9 is one , as is 17/9. Hopefully, you get the idea.

You can quickly move something into double format e.g. (5.0/9.0), (the default for a decimal number even with a zero in the decimal place is double).

Any simple binary operation involving one double and one integer, the integer is upcast to a a double and a double is evaluated. e.g. 5/9.0 and 5.0/9 are both doubles. However, 8/6.0 - 4/3 is not zero [it is 0.3333] because the 4/3 is done before - and produces an integer (1). The upcast is only for each pair in the expression and the expression is reduced.

So you can re-write sfou's cel = (5.0/9.0)*double(i-32); as cel=5/9.0*(i-32); . That is because (i-32) returns an integer.
then 5/9.0 must be done BEFORE * (since divide take priority). so we are left
with (double)*(integer) and from the rules above we have an double.

There is one final problem on the matter. In C++, there are several floating point numbers , float, double, long double. Which depending on the compiler/platform are typically on a PC. 32bit, 64bit and 128bit, but can be different. [You can …

StuXYZ 731 Practically a Master Poster

In reference to the previous post: Please clarify:

It is that you can construct a stack of operations which are either "read value" or "binary op", the effect is that you can construct a stack , then evaluated it, then make a permutation on it. Since the stack can represent all possible solutions, it is a very easy thing to compute with.

E.g Consider the problem of values item={1,2,3,4} and operators P={+ - *}, your stack is {V,V P,V,P,V,P}. this is evaluated to see if it equals T. Then just iterate the item list, and after each full loop, iterate the operators list once. Obviously, after a full step of both step you can change the operators.

That example can be optimized for cases were you have order invariance but the basic form is there.

On the other hand, if you try to make a stack with brackets e.g. ( A + B) * C etc. Then you have the problem of how many brackets etc. The stack is not obviously iterable. [It can be done, it is just seems difficult]

However, I may have missed the easy way to do this problem. [In fact I feel I have]

StuXYZ 731 Practically a Master Poster

Your problem is assuming that x1 and x2 are integers when you print them out.
Additionally, a,b,c are all likely to be floating point numbers. So read them in as floats. So make your output statement printf("%g and %g\n",x1,x2); Also you can use the sqrt function in line k=sqrt(d); .

HOWEVER: Can I just point out that using the formula given is a horrible way to calculate the roots to a quadratic equation due to the numeric instability of the solution. The "better" way is to calculate x1,x2 and determine which biggest root
(either in terms of magnitude or accuracy as a solution) and use the relationship x1*x2=c/a to get the other root.

There are further tricks to getting better roots from a quadratic equation, particularly if the roots are close, if b^2-4ac is near zero ,e.g a Newton Raphson step etc.

Finally, please use code tags.

StuXYZ 731 Practically a Master Poster

Assuming the problem is slightly more general you have a list of number e.g.
int items[]={4,4,4,4}; and you have a target number T.
Now you need to clarify the rules:

(i) are brackets acceptable: e.g. the given solution (4 / 4 + 4 )* 4 has to have brackets to get the problem to work. Since there is no solution that exists without that I guess you are allowing that.

If that is the case, the one way to approach the problem is to encode the operations and numbers on to a stack (reverse polish notation). Then you can iterate through the placement of a fixed number of operators and a fixed number of index values and
evaluate each step:
e.g. 1 2 3 + 4 * - ==> 1-(2+3)*4 =

Now it is just a matter of keeping the values in the list in order and iterating through the operators.

Finally, I don't think this is a good problem for recursion, simply because if the solution for some part is above/below the result it doesn't help, you could divide or subtract if you have an intermediate solution that is above the target. However, you CAN produce a recursive results. But it is has to implement a hidden stack.

Finally, what about a different language: this problem is very simple in lisp :-)

iamthwee commented: Lisp? I'll look into this. +12
StuXYZ 731 Practically a Master Poster

You are indeed correct things are not working correctly:

You problem is simple, you have forgotten to use a virtual destructor in baseClass.

All you have to do is add virtual baseClass() {} to your baseClass
and it will work.

However, please add virtual to your destructors of both your other classes. The general rule is ALWAYS add a virtual destructor if you have virtual functions of any sort. Otherwise you will have problems like this. [Most compilers warn you of this problem if you enable warnings]

StuXYZ 731 Practically a Master Poster

The problem may be that you have forgotten to remove the skipws (skip white space) flag from the stream. e.g.

std::cin.unsetf(std::ios::skipws);

If that is the case, then please also remember to return the stream to the state
you had previously. This is facilitated by setf() and unsetf() because both return
the state of the flags before the call e..g

std::ios::fmtflags flagIO=std::cin.unsetf(std::ios::skipws);
StuXYZ 731 Practically a Master Poster

"nameofbinary" is absolutely anything that you care to type. e.g. image we are making a program that I want to call "sumNumbers". You have written some c++ in a file called firstProgram.cpp and you want the output to be called sumNumbers. you would do this

g++ firstProgram.cpp -o sumNumbers

Once that had successfully completed. [If it doesn't then you wil need to edit firstProgram.cpp and fix the problem.] You can run it with

./sumNumbers

Note the ./ That is because you have to have a path in Linux to the executable.
Executable is a file that is to be run, e.g. the output of a compiler. Path is the places that executables can be found. The variable PATH contains all the default places that commands exist, e.g. /usr/bin in which you will find g++ and ls etc.
However, you have created the file sumNumbers in a directory that is unlikely to be in the path. Therefore you have to explicitly set the path in the executable line which you do by adding ./ or if you which the whole path e.g. /home/coding101/test/sumNumbers. Note this assumes your login name is coding101, but just replace that with your login name or, you can use the ~ symbol which just means home directory, e.g. ~/test/sumNumbers

StuXYZ 731 Practically a Master Poster

Your mistake is this

int random=(rand() % 20)+8;
strength=random;
dexterity=random;   // copy random again.

Random is copied twice.

Try this

random=(rand() % 20) +8;
strength=random;
random=(rand() % 20) +8;      // GET A NEW VALUE FOR RANDOM
dexterity=random;

Obviously you can remove the intermediate variable (random) e.g

strength=(rand() % 20)+8;
dexterity=(rand() % 20)+8;

EDIT: First_person just submitted it first -- he is correct (as well)

StuXYZ 731 Practically a Master Poster

I feel I have a slightly different perspective on this. Yes learning C++ itself will not make you a cool GUI program, but the library routines can be called from C++. However, the libraries keep changing, that is because we have new hardware, better algorithms, different OS which to build on etc. However, the C++ itself seems to have a slower rate of evolution. That makes the knowledge of C++ much more valuable.

Second C++ becomes part of your tool base, in my field, a large amount of numerical code is C++, some older stuff in fortran, GUIs [not that many] are in well java/python/ C++ with Qt/C++ with gtkmm. Scripting languages, we have R, python , lua to name a few, but they all end up calling C++ routines.

Unfortunately what is now required to produce a project, is a LOT of tools and knowledge, and that is before we get to the domain specific knowledge, I certainly would not have a job unless my Quantum mech. was at least passable, and I guess that every field has a set of domain information. That said, because I can code, I get a lot easier ride than if I had to rely on my physics alone, it improves review scores, allows me to have a lot more project options and employment opportunities.

Additionally, C++ is a very very large language, and one of the advantages I see, is that I can readily grasp these other languages and …

Nulled commented: Helped me get out of a stump... Thank you. +0
Ancient Dragon commented: nice summary +31
StuXYZ 731 Practically a Master Poster

Ok First off, there are two while constructions in C++ , do { } while(condition); and while(condition) { } There fore you don't need the do after the welcome statement.
In is current form this program should not have compiled.

You have written if(rNumber = uNumber) This is correct C++ but not what you want. It assigns uNumber to rNumber and then tests to see if rNumber is true, i.e. if rNumber is not zero. Therefore your code will always find this to be true except if the user enters zero.

The reason that you didn't find that error almost instantly, is that you have not enabled warning on your compile. If it is g++ then use the -Wall flag, if it is something else then please find out how to and enable it. Developing code without warning enabled for almost any size project will just take extra time debugging.

The rule is that any errors that you can move from run-time errors to compile errors are to the programmers advantage. This is the reason for much of the const correctness, for the type and cast requirements, as well as function/class definitions. Make use of this.


FINALLY: Please use code tags. [It is in the link at the top of this forum:
Read this before posting]

StuXYZ 731 Practically a Master Poster

Looking at your code you are almost 100% creating the array incorrectly.
And that may cause your problem.

By the looks of it you want an 2d array of dimension d and delta.
E.g. as if you had known d and delta at compile time you would have written int o[delta][d]; or the other way round.

int **o; 
// Allocate memory
o = new int*[delta*d];          // To much memory (?) 
for (int i = 0; i < delta*d; ++i)        // now over allocate again 
  o[i] = new int[delta*d];
// You have allocated (delta*d)*(delta*d) memory locations !!!!

Normally I would have expected to see:

o=new int*[delta];
for(int i=0;i<delta;i++)
  o[i]=new int[d];

Alternatively this is often done:

o=new int*[delta];
o[0]=new int[delta*d];
for(int i=1;i<delta;i++)
  o[i]=o[0]+delta*i;
// when o is ready for deletion:
delete [] o[0];
delete [] o;

Now your delete is correct for the allocation. However, you have two problems, did you really mean to allocate that much memory. It is very possible that you effectively have more memory that your system can cope with.

Second IF your got the array wrong, have you made a mistake elsewhere. You can check
if you put a std::cout<<(long int) o[0]<<std:endl; at the allocation of you array
and the deletion you can see if you have changed the memory location. e.g. have you deleted it twice.

Third: Common error, have you decided to zero the array AFTER you have deleted it?
That should not be …

StuXYZ 731 Practically a Master Poster

The problem is your copy constructor, for client.

So let us see how we get to that :
Line 5 of youf first program uses this: vektori.push_back(Client(account, firstName, lastName, balance)); This constructs a client object and copies it into the vector. With this line
you also call Client(const Client&); .

At this point you have a probelm: your Copy constructor is this

Client::Client(const Client& client) {};
// This does NOT copy the account number / the strings etc

Try writing this instead:

Client::Client(const Client& client) : 
   account(client.account),firstName(client.firstName),
   lastName(client.lastName),balance(client.balance)
{
   std::cout<<"Confirmation that copy constructor called"<<std::endl;
}

I would STRONGLY recommend adding an assignment operator. If you do not the compiler will add one for your AND because you are using string it will be 100% certain to be wrong [std::string allocates memory]. Always add a assignment operator unless you are 100% certain about not needing it. [Most of the time just add it anyway.]

It would be something like this:

Client&
Client::operator=(const Client& C)
{
   if( this!= &C)
     {
       account=C.account;
       firstName=C.firstName;
       lastName=C.lastName;
       balance=C.balance;
     }
    return *this;
}

p.s. That is an extremely well set out first post. Clear as to the problem, sufficient code to replicate the problem, but not excessive, and uses code tags. Thanks!

StuXYZ 731 Practically a Master Poster

Well first off do you have any code/pseudo code. I am surprised that you are going for pointers? (have you inherited from a shape class? and want to use a generic touching/intersect etc. However, that way you would not have onCircle but onShape.

I am not going to do this for you, so you are going to have to show some effort, but I am prepared to discuss a critical effect that you may have forgotten/overlooked, and that is accuracy.

It is only correct to say that two circle are tangent if they are EXACTLY on tangent and in the accuracy of computed numbers that is often surprisingly difficult to get.
So you are going to have to calculate the distance between the centres and the radius sum and subtract these two values, and they are considered to touch if they are within a certain distance. e.g

if (fabs(radiusSum-centre_centre_distance)<Tolerance)
   {
      // Circles touch
   }

However, your problems don't just end there, you have the additional problem that to compute the vector distance you are going to use squared numbers and that adds to you error (or a trig term e.g. tan, and that has its own errors). So yet more care is needed to avoid problems, unless the tolerance is large relative to roundoff.

Not what you wanted to hear I guess... but get some basic code together and present it, and we (that is the community here) will discuss it. You will learn a …

StuXYZ 731 Practically a Master Poster

Your problem looks like a lack of an extern + a scope error

Let me explain. You seem to "effectively" want to do this

int main()
{
   int var(10);          // this variable is local to main NOT the program
}

void foo()
{
   int a=var;         // THIS will not compile.
}

This is not allowed. That is because main(), as will all funcitons, protects its scope. So how to get round the problem:

int var;    // NOTE ABOVE MAIN

int main()
{  
   var=10;
}

void foo()
{
   int a=var;     // THIS is ok IF foo()'s defining is in the SAME file as main.
}

Well what if you want to have two separate files : For that we need the extern keyword.

// File Main
void foo();  // declaration 
int var;

int main()
{
   var =10;
   foo();
}
// SECOND FILE
extern int var;          // Note the extern keyword.

void foo()
{  
   int a=var;           // this is now ok and will get the value 10.
}

Hope that helps and question/comment please ask

Ancient Dragon commented: well said +31
StuXYZ 731 Practically a Master Poster

Several things come to mind: So I will start at the end of your code.

First is that (!(j % 10 )) . Is this true if j = 0.
Obviously that causes one of your output errors.

Now consider the getline function. You have told it that the linebreak character is
comma. However, when you read past the end of a line in your file, you get a concatenation of the two parts of the line e.g. you get 5\n12 .
You will see this if you add a std::cout<<"cNum =="<<cNum<<"== "<<array[i]<<std::endl; at the line your process cNum.

The if (dum[0]=='0') is obviously from a larger part of the program.

Finally: please read the posts about code tags, and please use them.
Please post slightly more complete code segements, e.g with the definitions etc.

StuXYZ 731 Practically a Master Poster

Ok as far as I know [And I have never coded on a windows box], it often seems that
beginners have the problem that they run the program, it creates a window, then closes the window when the program ends. That is not how it happens on a unix/linux terminal.

This sounds sort of like how you described it, so I suggested the std::cin>>i; as a way to delaying the end of the program. It you put a std::cout<<"THIS is my program"<<std::endl; as the first line after int main() { and you don't see it, then you have the problem.

If that is the case, then add the std::cin after the print statement and see if you
can see the output. If you do, all is fine and you can add the std::cin at the last
line of the program. [This assumes that you have not exits before the last line in
main.]

StuXYZ 731 Practically a Master Poster

My guess then is that you are running underwindows. Just put
a std::cin>>i; at the end .

You could also put some simple output like: std::cout<<"number of rows =="<<num_row<<std::endl; and make sure it says SOMETHING!!!

[You might even want to put that before you start reading the file.

StuXYZ 731 Practically a Master Poster

Two problems (initailly).

First problem: You are expecting two integers in the first line of the file.
I modified your file to have 6 5 as the first line.

Second problem: You are reading double precision number into and integer array. Not good. So remove your
definition of num_array, and then add something like this line: double num_array [max_rows][max_cols]; and your program runs successfully to the print array loop.

Since you seem to have figured out how to test in parts (e.g. by putting a print statement in as soon as you have done something. You should be fine with the rest of the program. Just move you print loops, down each time. [or put the print into a function].

StuXYZ 731 Practically a Master Poster

The problem is the while(true); iine and the } on the line above.
[lines 22,23]

The while loop does not allow you to go into the switch statement. Therefore to fix
it just move it to the line above you return 0; (between line 93/94).

StuXYZ 731 Practically a Master Poster

If the output is to the console/terminal. The you can do this

./program input_data > outputFile.txt 2> errorFile.txt

Note that I created and output file for the normal output and an error txt file for errors. You might want to put them all together with

./program input_data > outputFile.txt 2>&1

which just means put the output to outputFile.txt and then write the errors to the same place as the standard output.

Note that works on bash shells [default for ubuntu and most other linux distributions]


---------

Note if you actually want to pass the output to a file and process the data, you can pipe it and
use popen and associated pipes. You will need to include the unistd.h file and you can create a
file pipe e.g.

FILE* inputPipe;
 
inputPipe=popen("myProgram","r");

if (inputPipe == NULL)
   { // Deal with error }

char txt[MAXCHAR];
while (fgets(txt, MAXCHAR, inputPipe) != NULL)
   {
      std::cout<<"Data == "<<txt<<std::endl;
   }

There are more C++ ways to do this with boost and others.. but I am sorry I rarely do that so you will have to wait for a more experienced member to help you [and me] out.

StuXYZ 731 Practically a Master Poster

Sorry but there is insufficient code here to run, test and generally play with,
a bit more of a working example, e.g. something which runs would have been good.

But there are several things that might be a problem:

(a) Given the lines a=(s_axis_1+15)*10; and the similar one for b, did you really mean this. As s_axis is likely to between
-150 and 150 so a is going to be about 1650. Do you have an array overrun??

(b) Did you intend to do the same thing with b, it seems like the *10 was when the data was a flat single array, and you might have been doing int index= a+b; (c) This code doesn't seem to be right: (s_axis_1== -3.65541E-14) . It makes absolutely no difference in the present code (since you cast a to an integer) and any program that uses double precision should not expect zero to be exactly zero, rounding error is a fact of computing.


If you still have a problem can you make the smallest possible test program, even
if you use stuff like double s_axis_1=3.132e3; as the set up etc.
It will help us help you

StuXYZ 731 Practically a Master Poster

Can I add two more comments to this excellent post.

When you have the first answer, you may well be asked a few more detailed questions about your problem. Please try to answer them. Even if you are certain it is not the problem [you can explain that if you like -- that will help everyone.] This lack of interactivity, seems to kill posts dead, even though the original poster (OP) replies.

Often, the act of asking the question, leads to you discovering the solution yourself. Please don't just make the thread solved, with a "found the problem", please take the trouble to tell us what you did wrong. Even if it is brain dead stupid, we may laugh, but we all have been there and done it [and in my case, I seem to continue to have BDS moments]. You certainly will earn a lot more respect for admitting the error than the "found the problem" post.

StuXYZ 731 Practically a Master Poster

Well I can't repeat the first error. the board looks fine.

The problem with the second error is a simple mistake, so no problem. You wrote this

char coordinate[2];
cout << "What are the coordinates of the square: ";
	
cin >> coordinate[2];  // ERROR HERE:

You input the value into the THIRD coordinate of the char array. There is NO boundary
checking and there is obviously for any input a buffer overflow.

Your conditional test for coordinate[0] and coordinate[1] looks wrong.
Test that with "11" "AA" entries and I think you will quickly find the problem.

Finally: If I get this to mark, I would be deducting serious marks for the excessive comments. Do you really really need to write the functions in peudo-code and then write the same function? Please unless you absolutely HAVE to have such a pointless comment, write a comment that says what the function is going to do e.g.

/*
  editSquare:
     
     Param sudokoBoard : sudoku board 9x9 array
   
   - Takes text entry of a coordinate square from the user
   - Set the value to be text entered value from the user.
   - Simple error checking (none based on sudoku rules).
*/

The code and the pseudo code are nearly the same, it doesn't help to say i++; // add one to i .

The principle is don't repeat code, and don't repeat code in the comments.

Obviously this is broken by every C++ book because they …

StuXYZ 731 Practically a Master Poster

Ok there are two types of problem here:
(a) that you have made errors in your code that result in you getting the wrong answer,
(b) I really don't think you know mathematically what you want to compute.

I can address (a) easily and I will hint at (b).

Let us discuss (a):

First off: Consider your powerfunc: I have added some comments.

int 
powerfunc (int x, int n)
{
int x, n;  // RE DEFINITION OF X,N : Mask the version above: delete this line!!
int p, i;   // p and i can be ANYTHING use int i(10); say to set it to 10.

while (i <=n)
{
  p = p * x;
  i = i + 1;
  return p;         // NO :: This returns in INSIDE the loop
}
   // Only get here if  i's initial value is > n.
   // Shouldn't functions return a value???
}

So the main problem you have is scope. Your { } define an range that a condition/ function works. e.g

for(int i=0;i<10;i++)
    {  
     // ALL THIS stuff gets done 10 times
     for(int j=20;j<30;j++)
       {
          // This stuff gets done 100 times. 
       }
    }

In the example you see that you have two lots of scope. The part that the outer for
loop does is one scope and the inner loop is another. The inner part is done 100 times because its is done 10 time each time through the outer loop.

Please …

StuXYZ 731 Practically a Master Poster

First of all I have to agree with firstPerson's advice.

Second PLEASE don't use variable names like exp and the do maths operations. You are bound to at some point want to use the maths library (cmath). Then you are in a mess!!

Finally why not include the addition and other functions as a method of a polynomial class?

StuXYZ 731 Practically a Master Poster

Ok -- First off a little help with how big / and how much cpu you have available [and memory] would have helped. OS and compiler would be useful information.

however, if you get to 16minutes on anything remotely modern and anything remotely
under 250,000 lines of total code + comments you are likely making serious errors.

I will assume that your are using a Makefile with reasonable dependencies etc, if you are compiling your whole project each time, please please read about Makefile

First off: disentangle your include list. The biggest problem with c++ projects is that everyone seems to want to put #include's in .h files. Don't do it. It is MUCH better to see the list in the c++ file. Even if it is long -- It is easier to follow if you are looking for what is dependent and it is easier to see what has become bloated.

Second: Move stuff out of the .h files. If the code for a method is in the .h file (i.e. the class definition) it is going to be compiled each time the .h file is included in a file. That means template classes as well.

Third: Use explicit template instantiation. This is obviously not going to work if the product is a library, but will work if the product is an application since you have final control. That cuts a HUGE chunk off the compile time using g++.

Four: Now have …

StuXYZ 731 Practically a Master Poster

Looks like you have given us the wrong class. Your problem seems with arrayList not Sort. Which if you add a quick test, works.

StuXYZ 731 Practically a Master Poster

You mistake is here: dynamicArr ( dynamicArr& arr) {myLinkedList(arr.data);} What is happening is this. You are calling the copy constructor that MUST construct everything in the class BEFORE it gets to the part in the { }.

In the { }, you construct a copy, but then it goes out of scope..., leaving you with an empty list.

So do this: dynamicArr(const dynamicArr& arr) : myLinkedList(arr.data) {} That way you will not have to construct an empty linked list

You will have to fix myLinkedList as well.

P.S. PLEASE write an assignment operator like this:

dynamicArr&
dynamicArr::operator=(const dynamicArr& A)
{
   if (this!=&A)
     {
       // Your stuff here
     }
   return *this;
}

ALWAYS write a copy and assignment operator for all classes that have any dynamic memory, and then for most other classes. [Note: if you don't think it will be used then put the definition in the private section of the class]

StuXYZ 731 Practically a Master Poster

Ok I will make some very general comments about the structure of code:

First off: Always program to the smallest unit of work that you can do. i.e. don't try to factor your number / add to an array and print in one go. Start with getting one part of that correct. That could be the factorization, it could just as well be putting some numbers in an array, it can equally be printing an array.

Let me illustrate :

// TEST Print:
int main()
{
   int NArray[]={1,2,4,5,6};
   // Print part here:
}

or to test the placing numbers in an array

int main()
{
  int* A=new int[10];
  for(int i=0;i<10;i++)
    {
       int number=i*3+4;   // just make a new number anyway.
       // Code to fill A with the number here...
       //...
    }
  delete [] A;
}

So Jack. you are going to need to look up basics about how to allocate arrays, how to write loops [Which you seem to have go right], and please please space your code out with an indent for each level of a loop as sfuo has. That will really help you see the logic. After your have written some code , get it compiled. The smaller the quantity of code you write the easier it is to fix. If the hole code has been compiled, the with pen and paper, figure out what you expect your code to do. Then run it and put an output statement e.g. std::cout<<"Variable i == …

StuXYZ 731 Practically a Master Poster

Yes:

The 2001 ANSI standard added the erfc function ( 1-erf(x) ), for float/double/long double.

Not 100% sure when that got built into most version of cmath and math.h. But by now almost every compiler should have it, and should have had it for nearly 8-9 years.
Certainly it is is gcc/g++.

Not the best example

#include <cmath>
#include <iostream>

int
main()
{
   for(int i=0;i<50;i++)
     {
       std::cout<<"x == "<<i*0.1<<" "<<-erfc(i*0.1)+1.0<<std::endl;
     }
}

Please note : that erf has been added to a lot of cmath files, but I didn't know if that was in the standard

StuXYZ 731 Practically a Master Poster

Can I just comment (a) Jonsca is correct, you are going to have to define a tolerance and (b) it is going to be lot easier to calculate the cos(angles) of the triangle and go from there..

Also you cannot do this a==b==c It compiles but DOES NOT do what you think. It is the equivelent to this: if ((a==0 && b!=c) || (a==1 && b==c)) That is because b==c is converted to a boolean , i.e. 0 or 1 and then compared with a. So it will only be true if a==0 or a==1 and then if will depend of the result of b==c. If a=2;b=2;c=2 it will be false.

StuXYZ 731 Practically a Master Poster

Very Very likely!!!! - Never Never in use the default copy constructor unless you are 100% certain about what it does!! Even then don't rely on it!

StuXYZ 731 Practically a Master Poster

I think if you expect us to look at your homework, you should explain how your got to your answers.

Many of these questions are a bit vague and deliberately ambiguous , e.g. question 4.
Since there are only two points per node, you only update two pointers.

Anyway, you have at >5 wrong. So do some work and write some linked list so you understand this.

StuXYZ 731 Practically a Master Poster

If you are using gdb, then carry out the first operation I suggested. Then you have successfully trapped the exception. All you need to do is type up after putting a breakpoint in the global catch and you are looking at the line that caused the exception.

StuXYZ 731 Practically a Master Poster

Your real problem seems that your algorithm is too unclear. I couldn't code this up since I have no idea what is wanted and I think that is your problem too.

So what you are going to need to do is make this much more concrete: The quickest way to do that is to put down some numbers, i.e. program flow on paper!

So let us follow your current algorithm, you can then fill in the details and we can get back to a real algorithm.

x=10; y=20; z=30;   // set some values
// Now what happens???

So even if you can't write an algorithm [as demonstrated :) ], can we have an example. And in doing the example you will likely find that you can easily write the algorithm.

StuXYZ 731 Practically a Master Poster

Linkage errors:

Basically a compiler has several roles, that use to be done by different programs on the system [And under the covers, still are].

First the compiler turns your code into object code, this is basically assembler but without the correct calls to external data and functions.

Second the compiler then from a set of different object code, joins up these external calls. This is called linking.

You are using a Makefile. That is a method to avoid compiling all of the pieces of the code, if you only make a change in one part of the code. e.g. if you change your quaternion.cpp, then type make, I expect only quaternion to be compiled before linking. It will not compile Vector3.

However, if you change Vector3.h, then I expect Vector3.cpp to be recompiled, BUT if the makefile is written poorly, then Vector3.cpp might not get compiled and if Vector3.h has not changed much the program will successfully link and can be executed. HOWEVER at this point the memory to all Vector3 can be corrupt. That is linkage error. You can check it by deleting ALL of your .o files and re-making.
If the executable is different in any way from the original [before the deletion -- copy the original to a new filename, rm *.o */*.o, make, diff oldProg Prog ], you have a poor makefile, and linkage errors.

Note that linkage errors can also happen if you change a file that …

StuXYZ 731 Practically a Master Poster

There are several ways to do this: Everyone prefers something slightly different, and a fair bit depends on your environment, Linux, windows, embedded etc. But here are a few.

First : Debugger route.
The quickest way is to add a try { } catch(...) { // stuff here } around all the code in main(). That way you are guaranteed to get to stuff here.
Then run the code in your debugger, and put a break point at stuff here and back-track from there.

Better/Some debuggers allow you to put a break point on the exception being thrown, but depending on your code you might not want that, [i.e. if you handle a number of exception in other parts of the code and that is normal operation].

Option 2:

Valgrind is a superb (IMHO) memory leak checker, run the code with that and it will tell you were the error was, and maybe about other errors in the code. If you are on Windows, I am assuming there is something equivalent but you will have to google it.

Option 3 : Catch the exception and print out as many of the state variables as possible [e.g. outer loop counters, number of events etc] and try to find out when it goes wrong.

Does that help?

StuXYZ 731 Practically a Master Poster

Excizted:

Z term zero:

Sorry, some of my posts were a little confused since i incorrectly read the line in the debugger output. My mistake.

From your code, we are left with an error (or failure to write) a copy constructor
in Vector3, or linkage error. Since you by now have done a rm *.o/make clean or whatever, we are left with the Vector3 copy constructor.

By the way does this work:

Vector3 A(-1,2,3);
Vector3 B(A);
std::cout<<"B == "<<B<<std::endl;
StuXYZ 731 Practically a Master Poster

I think the issue here is first to define "big". What does that mean to you, size of an OS kernel (2million lines) , size of a big application (500,000 lines) etc. That gives you an idea of how much time a rewrite will take.

Next define the problem, why do you care how it is written: is it because you are not confident in the results or it crashes often etc., are you extending it to something else or adding functionality, or maybe you need to maintain it in its current state and just fix use bugs, or do you need your users to understand the code. [The latter is encountered say in scientific software, when you may need the users to see that the code implements the algorithms correctly]

The you want to define how complex the field of the program is, is it highly mathematical were algorithmic errors are likely, or maybe numerical rounding errors etc, or is it simpler [in algorithmic complexity] e.g. a GUI.

Once you and we have some of those answers this discussion can go forward. I seem to think that you don't need a c++ standard but more likely to want a static analysis, e.g. like the converity systems [note: useful but very very expensive]

Beyond that, I agree with the posts above, there is no such thing as "the standard", but a lot of things in a code that make me worry and the first one is …

Ancient Dragon commented: agree +28
StuXYZ 731 Practically a Master Poster

Several worring things here , but I am going to pick on one detail.
Your wrote this:

while(input[i]==input[j] && i<=j)
{
  i++;
  j--;
}

Now what happens with the simple word "a".
Let us see: First i is set to zero and so is j.
The while statements says that both input[0]==input[0] :) and that i<=j since both are zero.

Next i is increase and j is decreased:
Now what happens, now you are searching for input[-1]. That is converted into the operator[] for string, which takes an unsigned integer. Note that -1 is going to be a very very big number. At that point you are accessing memory that doesn't exist and you are hoping that nothing goes wrong -- but it can.

Fix the loop...

p.s. does your program pick up the last word in the file.

StuXYZ 731 Practically a Master Poster

Finally.... (I hope),

The rotation about the axis is better done this way.

Vector3
Quaternion::rotate(const Vector3& v) const
{
  Quaternion qV(0.0,v);   // Set the w part to 0, and the x,y,z to the vector v
  Quaternion RV=(*this) * RV* this->inverse();   // inverse: return the quaterion: w,(-x,-y,-z)
  return Vector3(RV.x,RV.y,RV.z);
}

The main reason for this is numerical accuracy. Note your input (for a rotation) is already out by 1e-4.

StuXYZ 731 Practically a Master Poster

firstperson:

No, it will call the copy construct since your are declaring the vector3 at that point. If you write this:

class AXX {
public:

  AXX() { std::cout<<"Constructor"<<std::endl; }
  AXX(const AXX&) { std::cout<<"Copy Constructor"<<std::endl;}
  AXX& operator=(const AXX& A) { std::cout<<"Assignment"<<std::endl; }
};

int main()
{
  AXX alpha;
  AXX beta=alpha
  alpha=beta;
}

And you get Constructor : Copy : Assignment .

Excizted commented: Thank you for helping and keep doing it. :) +1
StuXYZ 731 Practically a Master Poster

I am going to take a long long short here as to what is wrong;

You write

class Vector3
{
float y, z, x;
};

Note the order!! That worries me (slightly) since you are doing a copy construction
e.g. your line result=pre_result; will actually call the copy constructor and not the assignment operator (operator=).
The rule is that the components are initialized in order. Do you have some test that involves x,y,z in that order [e.g. a making the vector a unit vector etc.],

By this I means this doesn't work:

// WRONG:
Vector3(const Vector3& A) : x(A.x),y(A.y),z(A.z/sqrt(x*x+y*y))
{}

Gives junk result, since the order of initialization is y,z,x [in your case]

Addition to that I have you done a make clean . That is remade your vector class. Is it possible that you have missed the Vector3.h dependency from the Vector3.o in the Makefile. Then you have changed the order of x,y,z and then you get junk. If you delete all the .o files and remake, and it works you have just to find the dependency failure in your Makefile.

If you are using g++, you are using -Wall and you treat each warning as an error.

Finally, since you have a Vector3, why no create the quaternion with the Vector3 + W.

class Quaternion
{
  double w;
  Vector3 Qvec;
  public:
   // ..... 
};

Note that I have made your quaternion a double since any real use with …

StuXYZ 731 Practically a Master Poster

Re: degree of polynomial.

I am sorry I mis-read/failed to understand the code. You are correct, in that the code does indeed find the correct degree.

Obviously, that is work in progress, since you seem to be implementing degree, as a way to improve efficiency. [e.g. limiting loops etc], and to avoid array overrun, in the case of multiplication [e.g. x^51 * x^50 is a problem].

I hope it works out. Everything associated with polynomials seems to be very very expensive. [cpu/memory etc] For example : the representation of quadratic/cubic surfaces in 3D. The solution of a three surface intersect, reducing three f(x,y,z)s, even at only order 2, [e.g. x^2, xy and below] gives a 16th power polynomial and 16^3 (4096) coefficient operations to reduce it from three equations in three variables to one equation in 1 variable. That is extremely expensive!!

I do think that you can just change your array to double or complex and with a few minor tweaks continue. e.g. instead of coeff[i]==0 you can write fabs(coeff[i])<tolerance . You might want to consider implementing a maxAbsCoeff and set the test to be fabs(coeff[i])<tolerance*maxAbsCoeff but depends on the problem set.

As to recreating mathematica, I would just settle for understanding about half of the maths in it.

Anyway, many thanks for submitting this code.

StuXYZ 731 Practically a Master Poster

First off I commend you for investigating what I think is one of the most difficult classes to write. As always with a polynomial class, it is a case of compromises, and further improvements as scope and efficiency are improved.

There are a few aspects that I think the code would be better for.
First is that obviously polynomials are rarely integer, double or complex are common, and more interesting polynomials exist.

Second: Please don't do copy by value, use a copy by reference:

Polynomial minus ( Polynomial b )      // this copies a 100 integer array!!
{ }

it is better to write:

Polynomial minus(const Polynomial& B) const
{ }

I have added (a) constant and (b) B is copied by reference.

Finally, care needs to be taken with the degree. Often a polynomial system is being simplified. You would expect the degree to reduce in addition/subtraction. e.g
x^2+6x +3= 0 ; -x^2-4x+2=0 in addition make 2x+5=0 and the degree has reduced by one.

Basically, a polynomial class seems easy on the surface, but is horribly complex. There are significant problems along the way. Numerical issues abound, what do do about division, efficiency etc. Solutions, etc, special cases [quadratic->quintic],
and also do you want to handle 1/x etc.

What always seems to happen, is the the polynomial class is converted into a specialized polynomial class for the local use, and a different polynomial class ends up begin written for …

jonsca commented: Good suggestions Stu +4
StuXYZ 731 Practically a Master Poster

That is a bit field, so I can't really speak for all of it since I don't know.
First off there are not that many completely distinct OS , we have windows, unix (several flavours0, linux, BSD/Mac OS-x then stuff like OS-9 [it is in things like microwaves, digital watches, videos, washing machines -- if anyone knows the install base numbers please let us know! -- I have half an idea it might be the most popular OS, but don't know.

All of those have some assembly, a lot of C, some like windows have C++, which might be the dominate coding language (?). Cool operating systems like VMS, had BLISS which was the popular operating system language BEFORE C came along!!!

Application programming: Well that is just about everything, from high end functional codes, down to hacked together perl. In that context the correct thing to ask is what code base is most popular in a given field. E.g. if you want to be a CERN applications programmer, apart from getting your head round some scary physics, a large amount of that stuff is C++. Similarly, games are a lot of C++, you will find lots of java/javascript/php etc in web-based stuff.

The real question is why do you want to know, and specifically in what area do you want to know. That would give a much more focused answer. [Note: idol curiosity is perfectly acceptable...]

Since you posted this to the C++ forum, …

StuXYZ 731 Practically a Master Poster

I think that you have mis-understood what is going on in your if statements.

The condition if ('A' != 'z') is ALWAYS true for the standard ASCII character set. It is the same as writing if (65 != 122) which you can see is ALWAYS true.

Ok so what do you need to do. You need to test a range. Lets us first consider an integer value e.g.

int x=28;
if (x>10 && x<30)
  std::cout<<"X is between 10 and 30"<<std::endl;

As you can see I have two conditional tests combined with a boolean operator.
The if line first tests x>10 and then x<30 and combines them with an operator.

[NOTE: in C++ the compiler guarantees that it will test the first test first, and
that if it finds that the result is true/false without needing the remainder of the tests then it does not carry out those tests]

The && operator combines to results using the AND boolean operator.

For your test you can do this: if (ch>='a' && ch<='z') which tests to see if ch is between the ascii values of a and z.
Note that I have used a >= operator since obviously 'a' is a lower case value as is
'z'.

You could also use islower(ch) which is slightly better style because it deals with international character sets etc.

StuXYZ 731 Practically a Master Poster

Considering Nathans code: using int i.

Please don't use an int like this, input.size() is normally long int. You (a) should get a nasty warning. (b) it is an input dependent bug.. they are the worst kind so please code defensively for it.

StuXYZ 731 Practically a Master Poster

You should get an error with that code [Nathan's] since size_t is normally unsigned.
That means is it is always >0. Use a long int and a cast. Alternatively use an iterator.

You can also offset by one

for(size_t i=input.size();i;i--)
   temp+=input[i-1];

But I prefer iterators.