Additionally, please test it, then then see what happens as you change bits!!!
For example what do you think grandTotal = (subTotal) + waitressTotal;
and grandTotal = subTotal + waitressTotal;
would change?
Additionally, please test it, then then see what happens as you change bits!!!
For example what do you think grandTotal = (subTotal) + waitressTotal;
and grandTotal = subTotal + waitressTotal;
would change?
Ok first off please take a little more care with the code tags, but I can see you just made a mistake so no problem.
Second you open a fstream BUT write to std::cout...
Then next you can use fstream BUT if it is for output it needs
the std::ios::out flag to be set.
e.g.
file.open("StudentInfo.txt",ios::app|std::ios::out);
hope that helps.
Just about everything about interest is wrong.
Basics of percentages:
If you wish to calculate a percentage (P) from a total (T) you
need T*(P/100.0)
Your tax is 6.75 % so, you write totalTax = subTotal+tax.
Now the mathematicians say there are three numbers 0,1, infinity.
BUT the key thing to remember with any equation is to test those numbers. You should do that here : If you have a meal costing nothing [go easy of the water ;)], you would pay zero tax.
But you have an addition not a multiplications.
Total tax is the total tax, it should not include the meal value.
You also violate the precidence rules, the tip, is 15% of the (subTotal+totalTax).
Please keep it simple first time, do one part at a time, and use simple percentages so it is easy to debug.
They are both slightly wrong.
You are correct that if you delete everything from the vector, you have a vector of dead pointers. Obviously, a simple animatins.clear() would solve that (after the loop).
The second form does not call delete on the pointer.
Why not this:
std::vector<Animation*>::iterator vecIter;
for(vecIter=animations_.begin();vecIter!=animations_.end();vecIter++)
delete *vecIter;
animations_.clear();
Normally, a typedef is used for your storage class e.g. typedef std::vector<Animations*> animStore;
and that way you can change your mind about using a list or a vector etc. [But it is useful to use erase instead of clear, since lists etc don't have clear]
You can get round the problem by using a reference counted pointer. [NOT auto_ptr: it will not work] But a suitable boost pointer (shared_ptr). Note that the boost shared pointers are now part of TR1.
I wish to appologise. I think I have been very dumb. The S.o.E method does have a fundermental draw back. The only advantage is that it keeps the inital search under the machine limit for a longer time. This is not sufficient to offset the cost.
A naive search without dividing the target number down is obviously wrong route.
so returning to the original posters problem:
Algorithm should be:
i loop over 2->sqrt(N);
while (!(N % i ))
{
store i;
N/=i;
}
Then store N.
Note the while you need to check that the number doesn't have two or more identical factors.
hmmm I learnt something useful..... (as well as use brain before posting.. although I keep forgetting that!)
Thanks Rashakil.
His original problem was that he was doing just THAT
use successive trial division. There's no need to explicitly skip all the non-prime numbers.
Obviously, if you can do that quicly with a number like 600851475143, you have a seriously quick computer. That is just and only just in the standard PC / half-hour range, for older hardware and 32bit hardward it is in the 2-3hour range.
The reason for the orginal post (2 week ago ?) was that arun_lisieux was running on a slowish machine, and wasn't getting any output after a couple of minutes and thought that his program was broken.
So I stand by my original statement. I feel that I haven't been shown to be extremely dumb in this instance. [Although I accept that I am often :) ]
p.s. If I had set this as an assignment and someone handed in a simple loop, I would accept it, then add an extra assignment next week to factor say 15241580725499173 and that would turn 30min into a year or so -- and make the lazy student do a lot of work in a short space of time, while the others just changed the constant in their code.
p.p.s A good factor program takes 0.078seconds on my PC to do the 15...3 number above, a SoE based program takes 1.8seconds.
Algorithm is everything.
Small comment:
you can simplify :
for (int ii = 0; ii < 10; ii++) {
if (num[ii] > 0) {
answer3 += num[ii];
} else {
answer4 += num[ii];
}
}
calculating answer3 only so write
if (num1>0)
{ answer3+=num1; }
Then the negative number sum is answer4= answer3-answer1
Saves lots of typing.
Better would be to do the typing and check the answer!!
I was the original person who suggested using a sieve of eratosthenes. Now does this still hold? I believe so and here is why.
You were required to find the factors. The only factors of importance are prime factors, all other factors will be bigger since they are a combination of two or more prime factors. Hence you only need to test prime factors.
You now need a way to generate prime factors upto (at a maximum) the sqrt of the number. Then test them.
The SIMPLEST TO CODE method of finding prime factors is the sieve of eratosthenes.
In addition, the SoE is progressive, so after finding a new prime, it is tested and if a factor, the target number is divided and if the new target number is less than the square of the newly found factor, then the new target number is prime and the problem is finished.
I did then suggest that testing if a number is prime is easier than factoring and it is a good idea to test the target number first (because if it is prime then that is the end of the problem). [but this is a refinement of the original problem solution]
If you look a typical Pollard Lenstra number sieves, code for finding prime factors you are at >1000+ lines, that is serious code.
So Rashakil Fol please explain to us WHAT else you would do? you have said that I am dumb …
95% of the time this is wrong. The reasons are:
(a) classes with a virtual function you will get the wrong size (too big).
(b) classes that inherrit from a base class include the size of the base class but the pointer MIGHT NOT to point to the base class data area.
(c) If you have static objects they are not included (nor are they near the pointer in most representaions)
(d) If you have allocated memory (e.g. with a new) or memory that is allocated by a included object (e.g. std::vector) then you get the size of the pointer not the object.
So the way round it is normally to have the class write itself. (writeBinary is my normal method. I make it virtual)
Ok, three points :
Using pointer is required since you can't copy a filestream. That is because it is tied to resource. Yes, you can use pointers. Yes it is ugly.
Note that if you want to write the same stuff to a bunch of files then it is probabily best to use a stringstream and write at the end.
You really really don't want to force the program to open too many real fstream object, you would be better off having a list of filename, a buffer for each, and then as the buffer gets filled (and on deletion -- so you can be mostly certain to write everything), you write out to all the files requiring output. (a common buffer if that is more suitable is also fine).
You have made a couple of errors:
First the syntax of an if statement is
if (condition)
{
Stuff to execute
}
You have written
if (condition);
{ ... }
Your semi colon means that the test just doesn't matter. So remove the semi-colon.
Secondly, you need something like
if (condition)
{
do stuff if true.
}
else
{
do stuff if false.
}
What you have incorrectly (why does your compile not tell you which line?) is to put the condition (with a semicolon -- wrong again) after the else. You need to just write else.
Ok I have to compile for "target" machines that I don't have access to now and again [The horrible world of the hetrogenious grid :( ].
The first thing is to ensure that you produce a 100% static link.
use gcc -static which will cause errors if you try to violate that. That solves most of the problem. BUT you are going to run into even more since you have to get it to run on an old machine.
gcc-4.0 is 3 years old, and you have to make sure that gcc is not putting anything special into your machine code. So you have to have a close look at the output from gcc -v to make sure that nothing unsupported has crept in (e.g. sse2 for example, which will not be supported on an old machine).
First off I assume you are taking a course and haven't covered arrays.
Otherwize please use int num[10];
and a for loop.
But that is how to write this problem in 10 lines. It doesn't make you code incorrect.
What you have done wrong is use the comma separator between the numbers if (num1,num2,m3,num4,num5,num6,num7,num8,num9,num10 < 0)
What you need is to test each individually if (num1>0 && num2>0)
Finally, a quick note about the comma operator. It allows the evaluation of multiple values e.g. int a = b,c ;
will evaluate b and then c and set the answer for the evaluation of c into a. It is not used that often but when it is it is often only make the code more compact to write. [Expert comment: When it is overloaded it is outstanding, e.g Blitz++]
there are many horrible errors here:
The first that will take you a while to see (and most modern compilers would have flagged as a serious warning) is that you have while(done=true)
I am sure that you wanted while(done==true)
since the first while loop is ALWAYS true. Interestingly you define
TRUE to be 1 but then use true and false in your code. You are lucky that you get true/false from math.h.
What else: I work 39.5 hours a week :) But you use a lot of integers for things that can have fractional value.
How are there 56 weeks in a year?
Finally, the answer needs a bit of modification, Interest is paid daily and you can calculate the compound interest using a geometric series. e.g
[tex]
T = P(1+(R/365))^{n}
[/tex]
R is the fractional rate e.g. 5% is 0.05. n is the number of days, P is the principle and T is the total after n days. Note that banks normally use 365.25 as the divisor even if you savings didn't occupy a leap year.
hi
You have made a small error with your makefile. I think it is because you have mis-understood what is going on.
First off I have written <tab> to mean a real tab but it would not be clear if I had used one.
The lines of a makefile are
DEPENDENCY_SOLVED: DEPENDENCY_REQUIRED
<TAB>ACTION
Let us examine that with an example:
object.o: myObject.cxx myObject.h
<tab>g++ -o object.o myObject.cxx
This action says if you want to create object.o you need to find myObject.cxx and myObject.h.
(i) myObject.cxx or myObject.h are defined in the Makefile do their action
(ii) REGARDLESS OF WHAT HAPPENS AT (i) files myObject.h and myObject.cxx need to exist in the current directory, if not report error and stop.
(iii) IF ANY of the dependencies looked at in (ii) are NEWER then any existing object.o THEN run the action.
so to correct your Makefile you need
Code3: $(TOOLSRC) $(TOOLSINC) makefile
<tab>$(CXX) -o Code3 $(TOOLSRC) Code3.cxx
Let us know if you need any more clarification
CPPRULZ: I often require that the program says 16.0f 16L or some such thing.
There are three reasons: (a) to be clear about what sort of number is being used. (b) to avoid implicit conversions, (c) to help control/understand/document roundoff error.
(a) Often comes about in cases when we have maths libraries providing mathematical functions e.g. sqrt(2.0L)
is different to sqrt(2.0f)
.
It gives the reader an idea about the numerical tolerance later.
(b) If you have class A { A(const int); }
and you have A x; x/3.0f;
. You can avoid a conversion and add some type safety (an explicit would also help).
(c) You often need to "remind" the reader that the function is of low numerical accuracy. (e.g. return ans/16.0f;
)
I am sure there are others that people use but I can't remember.
gcc-4.3 is getting MUCH picker about weak down conversions, I think it is how we will be going.
well that sort of works..
(a) you still have a junk code calculating the number of days.
(b) you have functions that return values BUT don't your compiler should tell you about that. -- NEVER allow warnings to go through.
(c) Think about what happens if day==31 in putEntry.
(d) you are forgetting in several places that C++ arrays count from zero and not 1.
Well start with the second first. If the memset is in your assignment and you can't add code in the lines above it then 100% of this class can't fix the error.
The first: If you call an operator= what you are doing is getting to say how A=B is done. Therefore what it does is EXACTLY and ONLY what you have in your operator= method.
Therefore, it only does what is in your code, line by line.
String& String::operator = (const char *other)
{
if(this->m_buffer!=other)
{
if(m_buffer!= NULL)
{
delete [] m_buffer;
m_length=strlen(other)+1;
I have extracted the code and will go through it line by line.
First line is the function entry point, other is set to a value, let us say is 0.
Then we have a test, assume that this->m_buffer=0x4535.
That is not equal to 0. So the test passes.
Then we have another test (line 6) , well 0x4535 is not 0 so that also passes.
The (line 9) you have strlen(other) and strlen(0) is a seg fault.
oK... were to start....
(a) daysInMonth should be a simple function
static int Days[]={31,28,31,etc};
if (logMonth==2)
{
//process leap year (carefully)
}
else
return Days[logMonth];
}
This code is much better written as a static function that takes a number. You will need it when you write dayInWeek but not for the month that you are in.
(b) Your error in put entry is that you check the day against the logMonth (ie the 13th is never going to work!). And just in case you set a local variable called day =1 first [was that a debug line??]
(c) The constructor : No tests what if I accidently call it with Logbook A(0,0);
.
then obviously you get MAXDay and promptly don't use it. But the function doesn't need to use MAXDay. Since your array is ALWAYS 31 entrys so just use:
for(int i=0;i<31;i++)
entry[day]=0;
Finally, return exits the function, so there is no need for a break afterwards. [Actually the is no need for the horrific case statement... ].
Nor sure what you are trying to do here.
I would like to see logbook.h and logbook.cpp please.
Oh dear.... This doesn't look very tested....
Line 18/19 Do you really want an if.... I think this is required
for(;i<arraySize && savings[i].accountNumber!=NULL;i++) ;
and you always increase the arraySize regardless...
and you do absolutely nothing if i==arraySize....
hmm.....
oh and classic errors on the both while loops since you never increase j or k.
Overall a slightly better attempt, but you didn't go for my second psuedo code version
which is a shame since you have code repeat with different errors and hence twice the debugging to do.
Anyway, enjoy the debugging ....
Well let us see the answer then !!!!
This is not much better.
(a) size++;
(Line 22) I think that should be arraySize.
(b) You have a for loop with i, (line 17) . Then you do not allow the loop to continue but have a while(i<arraySize)
. Oh yes and the for loop is actually i<=arraySize
because of the indirection of setting len=arraySize.
Then just incase this isn't a winner for the obstaficated c++ contest, you have another while further down using the same variable .
This is 100% a mess.
Then you have a loop in a loop using the same index variable.
Summary:
(A) Bin this code -- This will save you time.
(B) Do the job in stages:
(i) Find the first savings which has a null accountNumber.
call that variable Index.
(ii) Then have two pieces of code
If (Index<arraySize)
{
copy new stuff in to place.
}
if (index==arraySize)
{
increase arraySize by 10
copy new stuff into place
}
Looking at the above you can easily see that it should be
If (Index==arraySize)
{
increase arraySize by 10
}
copy new stuff into place
Job done, time for something else. [Writing your unit test]
Ok without a lot more of this program I am guessing. BUT it is obvious that many things need to be fixed.
(a) The start? const int len=arraySize;
you don't change arraySize until the last line ? so why len?
(b) The first while loop [CHECK for i>=number of savings]:
Try:
while(i<numberofSavings && savings[i] &&
!savings[i].accountNumber)
{
i++;
}
The next if (savings[i].accountNubmer==NULL)
well it can't possibly be true in your code.
Then is gets REALLY scary:
You delete ALL savings and then create saving +10 .... (this isn't a copy) and then you assume that everything is ok
Then we see that you allocated temp REGARDLESS of what you thought you were doing, and you are hoping that constructor populated everything perfectly???
Finally, you input data and return data WHY?
Summary:
This is such a mess. You should post the whole project. BUT before you do you should format it differently. It should have each { and } on a new line. It should be space indented so you can see your loops.
You should look at breaking things into smaller functions. E.g. Adding an extra 10 accounts. Do this with a function, then the coping etc. can be done away from the other logic and then you might be able to follow your own code.
It is simple you HAVE to simplify your code so you can easily read it thought and know how the variables …
Sorry I am not sure that boost has anything that you really want.
But the Gnu scientific library, has the structure for coordinate transforms (all the matrix stuff + differentuals). And the octave library, (which needs a little care to extract)
has a host of coordinate transforms.
Salem + Me have pointed out two different points in the code that you have errors:
From you last post:
You have if(m_buffer!=NULL)
BUT you don't have if (other.m_buffer!=NULL)
. You can get to the line m_length=strlen(other.m_buffer) + 1;
with [B]other[/B].m_buffer == 0
That is why THAT piece of code doesn't work.
Then you have to fix the error that Salem pointed out. You have a memset() without allocating the memory which is written to by the memset. memset sets memory it does not allocate memory or check that the pointer passed to it points to suitable memory.
In comment about your ACTUAL code.
The error is that you have a continue
.
This is not what you want since it continues the loop. It does not reset i. You can see this error with a simple cout on the start of your for loop.
I am not going to say you need a break
. (although it works, the code structure is awful.) Why even test numbers like 1. Surely any integer has this as a factor.
This is a problem that requires thought NOT code.
The answer can be easily found on a piece of paper.
So without giving you the whole solution try thinking about this
Obviously 20! (20x19x...1) is a solution but it is not the minimum.
Now you have two types of numbers primes and non-primes:
2,3,5,7,11,13,17,19 : so your solution has to be a factor of
2x3x5x7x11x13x17x19 == 9699690
[Sorry I actually did that on calculator ;) ]
Then it is easy, all you have to do is find all the prime factors of each other number and find the lowest common addition to the prime list that you already have. Then you have your answer.
E.g. for the above consider 6: it is 2x3 so no addition is required.
But 4: is 2x2 so you have to add at lease one 2.
That is a much much better way of solving the problem, particularly because if I was setting the problem, next week I would add that I want the lowest 1-1000, and brute force methods will die.
The obvious stuff is wrong : use of '\n'
rather than std::endl. the complete lack of tests for input values.
e.g Would this be wrong
IntStack stack(-40);
so that is why you have a problem with IntStack stack(0)
since you initialize p=new int[0];
and then things are not good.....
You should have checks on all the input of the public function, that includes the constructor.
Also it is normal in stacks to have a separate top() and pop() function. That is because what should you return if the stack is empty ?
you have more problems in the assignment constructor. [in addition to horrible code repeat!]
e.g.
m_length=strlen(other.m_buffer) + 1;
m_buffer = new char[m_length];
strcpy(m_buffer,other.m_buffer);
Now consider what happens if other.m_buffer is a null pointer. That is a seg fault.
The worst error here is the lack of virtual destructor. The WRONG destructor is called. Regardless of you writing you own or letting the compiler write it. Doesn't matter.
So you should have
class customer
{
public:
customer(string N, int c); // << -- Added
virtual ~customer(); // << -- Added
string name;
int callNum;
void set_values(string N ,int C){
name=N;
callNum=C;
}
virtual float compute_bill() { return (10+(.5 * callNum));}
};
Technically you do not need a virtual destructor in premium_customer UNLESS you inherrit from it. BUT you have no idea if you / someone else will do so. So just add a virtual destructor as well.
Virtual functions:
Quick summay. Virtual function allow the following construct to work
class A
{
public:
void fncX() { std::cout<<"A:fncX"<<std::endl;}
virtual void fncY() {std::cout<<"A:fncY"<<std::endl;}
};
class B : public A
{
public:
void fncX() { std::cout<<"B:fncX"<<std::endl;}
virtual void fncY() {std::cout<<"B:fncY"<<std::endl;}
};
int main()
{
B itemB;
A* ptrA = new B;
B* ptrB=new B;
itemB.fncY(); // prints B
itemB.fncX(); // prints B
ptrA->fncX(); // prints A
ptrA->fncY(); // prints B
ptrB->fncX(); // prints B
}
Note the difference in the behaviour if you have a point that is being stored in a base class.
In your case you have a base pointer that stores a derived class.
There are many many things wrong with this.
Let us start with MergeSort.
Ok explain
int k = 1;
for ( i=0;i<k;i++)
{
q = q->next;
}
Ok we have (A) a global variable as a loop index !!
(B) a loop that never does anything more than
q = np->next;
Then we have three (!!) while loops
Then we have a piece of repeated code in the if(q->info < p->info)
if/else construct. Likely to cause errors later.
The we have a while loop with a first line break / So what about making it part of the condition OR was the intention to escape higher.
Then you break out of the while loop on the condition that q IS null
and then expect p=q and q=p->next to work.
Overall, this is a mess. Sorry, I think you compeletely miss understood merge sort. The normal structure is something like three whiles but not embedded. Try http://en.wikipedia.org/wiki/Merge_sort
to see how.
Without a bit more code this isn't going to be easy.
I would guess that the error is two different Color classe. It is very common in things.
I will add I would start by using std::map<> etc, and not using using namespace std;
The use of List and Map as variable names is horiffic. Name them as something related to their use. I can see they are a map/list.
Well pointed out iamthwee, you are completely correct. about eh
BBP formula. Sorry for getting that wrong.
As to using partial sums... even with the midpoint sum the number of terms required is huge -- but point taken!
Your code is slightly ugly since you have two levels of derefrence and that can slow down understanding.
There are several methods that can be used. But what about using a policy class
class Conv1
{
public:
static const int data[];
};
class Conv2
{
// same declaration but different data.
};
template <typename T>
void Convert(const std::string& s);
{
if (T::Data[0]==54) {} //etc
}
int
main
{
std::string A="fred";
Convert<Conv1>(A);
}
There are bits you are going to have to fill in but the idea is there (I hope). Obviously, it is possible to put a convert function INTO the classes Conv1/Conv2 etc, if the convert is significantly different.
You can do this by the basics functor approach but would want inherritance to get the same basic convert function but again that adds complexity for your example.
This is the worst assignment I have ever seen.
The series is the Geogory-Leibniz series. It is one of the slowest convergent series for pi. You need about to sum 300 terms to get 3.14 accurately, to get 10 digits you need about 10 billion terms and to get to 1000 digits you are in the realms of needing more computations than atoms in the universe (by a long way!).
I note that there are some transforms that get the convergence quickly (see wolfram site) , if that was the intention of the question, fine, but otherwise it is a very stupid question.
If you want to get pi accurately then you can use Brent–Salamin algorithm http://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm
formula.
But this is a computing forum so I HAVE to give credit to the
Bailey–Borwein–Plouffe formula.
pi=\sum_0^\infty (\frac{1}{16^k} (
\frac{2}{8k+1}- \frac{4}{8k+4} -\frac{1}{8k+5}-\frac{1}{8k+6})
This allows you to calculate JUST one digit (in hex) at a time.
Stunning in its elegance!!
Before you get strangled with compiler errors. Please note that in c++
you write public:
Then all things below are public (until either the end of the class or one of private:
or protected:
The reason I am flagging THIS error up, is that the compilation error you generate is likely to be completely indecyferable.
Complete diversion : [P.I.M.P please ignore (sorry)].
VernonDozier said:
There's no function in C++ that can retrieve the length of an array.
Now I would have agreed for the last 20 years BUT last week I saw this:
template<typename T, int size>
int getArrayLength(T(&)[size]){ return size; }
And that works in a simpler context (ie the given situation)
#include <iostream>
template<int size>
int
func(int (&X)[size])
{
std::cout<<"X == "<<size<<std::endl;
return 0;
}
int main()
{
int A[50];
int B[80];
func(A);
func(B);
return 0;
}
Try CC = g++
and CFLAGS = -Wall -g
BUT once you have changed them is it 100% essentual to do a make clean
before your make all
. Otherwise you will fail to implement the change.
Coming back to the original post. (sorry).
I think it is a level of depth. For Java, yes you do GUI/ graphics from a previously written library. For the c++ you are seeing a deeper part of computer programming, i.e. the lower level, the bit that builds the library. If you do more embedded stuff, you would learn assembler.
Interestingly there is a shift between the [old?] self-taught programmers who did basic (until aged 10) - assembler - C - C++ - Java, and the CS programmers who did Java-C++-C-assembler in that order. The self-taught know that the CS people don't understand pointers/memory correctly and the CS people know that the self-taught spend way to long programming something that is a one line library call, [even if it isn't exactly what was wanted].
Your course, could have done it the other way around (C++ first then java), but java hides some of the pointer stuff from you.
It is important to code at the lowest level required and no lower.
For my work, we use absolutely no java, it is 85% c++/fortran, some Schema, some Octave, but then I do numerical stuff that burn a few 1000 days of CPU per run. The graphics are C++ but so much of the rest is, it was a natural extension.
Would we use java? just for the graphics (had we not had to build the numerical engine). Yes! Could we do the numerics in java, maybe …
Please don't use rand() for anything but test applications.
This is especially true if you have strong consequences for short sequences of very high/very low random numbers. Additionally, if you need randomness immediately, for the first few numbers, then don't use rand(). [Especially since most people random number seeds are way to short which accentuates this problem].
If you need a random number generator try Merseen Twister.
http://www-personal.umich.edu/~wagnerr/MersenneTwister.html This is a c++ versions.
The advantages are that is passes TestU01-Crush and that is not something many random number generators do. Additionally it is only about a little slower than standard rand().
Two things to consider, there is a 32bit and a 64 bit version. (you can use the 32 bit on a 64 bit and visa-versa but you loose speed or stride).
If you need a faster random number generator, there is a fast SMTF algorithm but it is 128 bit algorithm. That is fine for modern chips (>about 2005) BUT not everything. i.e. So be careful when sending to a hetrogenious cluster.
Acutally this is a "classic" interview question. (Which I have never used/heard).
You start with two pointers, you advance one two time, and the other one time. If you go past the end, you set it to the first item.
If the two pointers match at any time before the last item of the list
then you have a loop.
The special case if a cyclic loop which is true if the two pointers match on the last item BUT the first pointer hasn't had to be jumped to the start of the data.
Basically, there are two scales in the problem based on the initial conditions.
The first is that the planet and the start are going to orbit each other.
The second is that the planet is going to escape on a hyperbolic or parabolic orbit.
You can test the possiblity of either (a) or (b) by calculating the total energy required to separate the bodies to infinity, and the summing the kenetic energy. Obviously the P.E is
[tex]P.E= \int^\infty_d \frac{GmM}{r^2} [/tex]
[tex]P.E= \frac{GmM}{d}[/tex]
were d is the initial distance and I have replaced your F with the more common G.
Now you can get the ellicity of the orbit from energy considerations,
consider the reference frame with the heavier body motionless, then
[tex]
\frac{v^2}{2}+\frac{GM}{r} =\frac{-(GM)^2}{2L^2}(1-e^2)
[/tex]
were L is the relative angular momentum and e is the ellipsicity and is the number you are after as it gives your scaling value. (using r as the distance)
Note this can be obtained using Newtons laws and a Lagrangian and is readily availiable on the web. (and is longer than I can write without making stupid typo.)
Now once you have the ellicity you know how to scale your problem since it gives you the max/min distance. I would choose the min and rescale, Note that if the ratio max/min is getting greater than 1e6 then you are going to need to do it in a log …
The first thing you have to correct is the class englishwieght::getnumber()
etc in your def.h file.
It should be a .cpp file and you need float englishweight::getnumber() etc. Not class. Note that by spelling it wieght
and not as you spelt it in the first part of the program you avoided a name clash and the compiler accepted it.
(If you use g++ you get some very very serious warnings about this!).
Just to be clear.
The problem is that you have allocated an array as user users[2];
. This gives you two user objects. They can be referenced as users[0] and users[1].
When you start doing users[2].logonName;
etc, you
have corrupted the memory of your program and what happens next is pure chance and unpredictable. (and normally bad!).
So increase your array to size 3, and then fix the loop which needs to be for(i=0;i<3;i++)
Don't feel too bad, as always, when anyone starts on classes they seem to overlook the simple stuff for a while. [It will come back to you in a bit.]
This isn't something simple, i.e. that you output nothing in what() and
then you are double throwing the exception.
You are always going to get
terminate called after throwing an instance of 'std::exception'
what(): std::exception
with this code, it is just a question of what you are going to get first.
you can test that by getting rid of the throw e; (on the second catch) and replacing it with exit(1) [if you need to exit]
Ok : Let me deal with the first and possibly the most important problem.
Inheritance is normally an "is a" relationship. Yes it can be broken but if you do, then you always explain yourself, [either in comments in the code / or when you post and say something about it in you post]
Now students are not course. A student is not a course in almost all normal layouts. So don't inherit.
Certainly a course can contain a number of students. And equally a student can B]contain[/B] courses (normally as pointers but maybe not).
OK that over: It solves your problem.
You could have a class register. That has all the students who are registering. The you have a class teaching. That container all the courses. Now students then get a pointer to a course (or several)
and then courses get an array of student pointers.
Then when you delete both student and course. you do nothing in the destructor.
Note that you will have to delete both register and teaching together, so maybe make them one class. I would also make them in a singleton. (If you are not familiar with singletons don't worry about it now, just create one instance of the class globally. Then it will be deleted on the exit of the program.
Not have another go at writing this. you will have to post a little more code and we will see were you get …
Sorry I am going to be harsh. This is by far and away the worst prime factor sort that I have EVER EVER seen. Do not code until you have considered the maths.
Consider a number[TEX] N[/TEX]. (which is a positive integer)
First if a number has a prime factor, [TEX]p[/TEX], e.g 2,3 etc. The biggest prime factor is either [TEX]p[/TEX] or the biggest prime factor of [TEX]N/p[/TEX].
That allows you to reduce the number you are searching for by a long way.
Second, from the first rule you can deduce that the largest value you need to test is the [TEX]\sqrt{N}[/TEX] [rounded down to the nearest integer]
Pseudo Proof :
consider two prime factors: [TEX]a,b[/TEX] such that [TEX]ab=N[/TEX], then if [TEX]a=N^{1/2}+x[/TEX] and [TEX]b=N^{1/2}+y[/TEX] obviously [TEX]ab=N+xy+(x+y)N^{1/2}[/TEX].
[Note [TEX]x^{1/2}[/TEX] is the same as[TEX] sqrt{x}[/TEX] ]
So why does your problem return a blank screen --- because it is using billions and billions of CPU cycles and expanding a vector to an unbelievable size.
Finally?: Your code doesn't even give the right answer! Try 121 as the input value.
Finding prime factors from large numbers is an extremely difficult thing to do. (and extremely CPU + memory intensive). But there is a lot of literature on this, and a lot of improvements over Eratosthene's sieve method, but to make it an O(N) worst is impressive :)
How to proceed
So I would start with a simple routine to check if …
Ok Let me try to get some order:
You have a line class2 ** PointerClass2;
Now that means effectively that you have a set of pointers that point to arrays of objects of type class2. The use of class2 is irrelevant to the problem ( I think).
Now then you put PointerClass2=new class2*[size];
but that is not in a constructor but in the definition of the class so it can't work. Let me assume that you wanted it in a constructor.
Then you wanted to write a delete operator for the class.
As ALWAYS, how you allocated tells you how to delete so I cant really answer your question but let me write a simple class for you. The you can tell us what is correct/wrong with my assumptions and we can go from there.
Note : I have dropped using classXX since it is just too easy to read it incorrectly and get confused. It is not just you that this going to be reading this code.
class A; // Predeclaration:
class B
{
private:
A** Ptr;
public:
B(const int arrayLen,const int NArrays)
{
Ptr=new A*[NArrays];
Ptr[0]=new A[NArrays*arrayLen];
for(int i=1;i<NArrays;i++)
Ptr[i]=Ptr[0]+arrayLen*i;
}
~B()
{
delete [] *Ptr;
delete [] Ptr;
}
};
Note that that is how you would do it if every array that is stored is the same length. If not then you are going to need an explicit loop in the destructor (and a modified assignment).
This is a …
If you are using linux, there are a few tricks to make life MUCH better.
I am assuming that by debugging you mean the error messages that gcc/g++ give you when you compile your code. [Not, how to debug you code are runtime, which gcc facilitates but doesn't do]
Ok first there are IDE's for linux (e.g. eclipse). I don't use them since I hate being confined to so small a number of views of the code and I like emacs/gcc.
Second: Learn to use make. A simple make file for each project is a massive saving in time. [and vim/emacs both support building from it, if that is how you want to work]
Now if you are using gcc native. There are some ways to make life better.
(a) Know that you can pipe the errors to a file e.g. g++ file.cpp 2> error.log
. The advantage of this is that you can the edit the file and I use vim to edit the error file.
[along with a :set nowrap] and everything looks lots better.
(b) gcc gives LOTS of warnings. Be prepared and build up you code in small fragments and REMOVE all the warnings by improving your code.
(c) Use g++ -g and don't do -O or -O2 since you want to debug it easily, while developing.
(d) ddd is your debugging friend!! Compile with g++ -g and no optimization and the ddd program.
Finally, the …
Let me see now your first post you were told that we don't help with assignments unless effort is shown.
THIS post you decide to ignore that reality and persist in asking please do my assignment for me.
The ONLY way you are going to get help is to actually show some effort.
The only good thing about your post is that you are likely to be competing with me for a job when you leave university and I fancy my chances since you can neither code nor learn. [Although I am worried about some of the other very knowledgeable posters ;) ]