StuXYZ 731 Practically a Master Poster

Well you don't seem to have written a operator>> for class ballTeam. I could be wrong since you didn't include the definition files (.h files).

I

StuXYZ 731 Practically a Master Poster

This is code absolutely begging for a loop!!

Your actual problem is that you test x then y. That is incorrect. (I think)

Consider a box with coordinates (0,0) and (10,10). I.e it is a square of area 10. Now what happens when you ball is at
(5,23) obviously that misses BUT in your code the first test accept the
point as if only checks the x value and not the x and y simultantiously

You need

if (ballx1 >= boxes[0][0] && ballx1 <= boxes[0][2] &&
    bally1 >= boxes[0][1] && bally1 <= boxes[0][3]) 
{ }

Then just put all 5 box test in a loop please!!

The reason that you should use a loop is that in the copy paste you have made a mistake with boxes[4] and boxes[3].
Note: that line 49 says dirx and I am 99% sure that should say diry.
same with line 39.

StuXYZ 731 Practically a Master Poster

The problem you have is temporary values and what happens to them:
I think this will be clear (I hope :)

The problem is that your are taking a copy of the value in the list. This does indeed correctly delete the object. BUT then you do v=0 rather
than *vertexListIterator = 0 ; . Now you access the value in the list, which you have not erased, and then you access the memory area that you have deleted BUT that memory space is marked as deleted but is unlikely to have been over written so you get valid results. If you had done lots of other operations then you might get different results.

Note that if the list was just list<int> and the values were 1,2,3, you would not expect this to change the list:

for(list<int>::iterator ai=L.begin();ai!=L.end();++ai)
{
    int x= *ai;
    x=4;             // This doesn't change anything in list
}

The normal process that would be not to use the temporary.

delete *vertexListIterator;
*vertexListIterator=0

Also please please don't use the C style casts, use a static_cast. That would remove any problems that might arise in-case the list turned out to be of a polymorphic class, and Vertex wasn't the base.

You use reinterpret_cast<long int> in the output of the pointer value to be printed.

schnell commented: Good Explaination +0
StuXYZ 731 Practically a Master Poster

If you are debugging code (and that is what you are doing here), you need to step through the code and check your assumptions. That can be done with a traditional debugger that lets you see each line as it is run, or by putting some output statements in the code.

Your errors include
(a) the loop for the factorial never is run. since neither N nor i are changed in the while loop. This should be fairly obvious since you never reached the "factoraila == " statement

(b) you are using a loop to calculate [tex]\sum n^2[\tex] ?? There are simple formula to get the result, no loop.

StuXYZ 731 Practically a Master Poster

First things first: Dont use system("Pause") it has been discussed to death here and everywhere on the web.

Second: The next problem is that you are using temp1 without initializing it. i.e every time you run the program it could start with a different value and you don't know what it is.

Third: you use a struct student, BUT by not having a constructor in this object all the variables DO NOT GET INITIALIZED. Therefore your have another problem.

Four: You really really need an array of students. it would make the code MUCH shorter.

Five : Semi colon after the while (ans=='y' || ans=='Y') ;
is wrong. because then the while does nothing, or loops indefinitely

Six: the reason that your class_ave does not work is that your pass three uninitialized variables. Then you have the logic wrong. Ok. Consider that you wish to pass up to three students, then temp_1 etc
should be the three values the students get.
You might chose to do that like this

// THIS IS IN YOUR MAIN:
class_ave(record1.total,record2.total,record2.total);

Note, the thing that is getting you mixed up is that the values or VARIABLES that you use to call the function are not the same names as are in the declaration of the function, you can equally call the function like this
class_ave(40,45,34);

Note that you have then made another error. Your values in are int. This is not correct, since you are taking an average percentage on …

StuXYZ 731 Practically a Master Poster

The normal way to do this is to use a stringstream.
Now you have to be VERY VERY careful, with this.
The reason is that if you do

double Res;
std::string A="3.4e5x"
std::stringstream IX(A);
A>>Res;

This cose will happily set Res equal to 34000. Which is not correct.
So Try this:

// This function returns true if the number is valid
// and sets Res to the correct number
template<typename T>
bool 
convert(const std::string& A,T& Res)
{
 std::istringstream iss(A);
 iss>>Res;
 return (iss.fail() || iss.tellg()!=A.length()) ?
   false : true;
}
StuXYZ 731 Practically a Master Poster

Ok there are many many thinks to really really dislike about this code.
In particular is the "cleverness".

Ok first, it is int main() . That has been said a million times on this forum.

Second for (sigma=ii=0;ii<n;ii++) thsi is C++ so (a) reuse index i and declare it in your loop like you have done for the first loop in your code. Second the "clever" sigma=ii=0 is a mess since (i) sigma is a double and ii is an integer and you would have been lots better to write double sigma(0.0),sigma2(0.0) ... etc. on the line above.

Then you make a mistake -- your see scores points the first point in the memory you allocated and you proceed to change that by using it as a point -- so by the end of the first loop (to get mean) you have scores=original_scores + 5 * sizeof(int).

The you don't reset it --- oh --- that means that the next loop is junk, since score loops over the NEXT 5 values that can be absolutely anything.

Finally you allocate memory so please remember

For every new there must be a delete.

You are well able to fix your code by (a) using array indexs e.g. scores or (b) by using a new pointer that is not allocated e.g

double* sPtr=scores;
for(int i=0;i<n;i++)
    sum+=*sPtr++;

Finally: Do you know that the line strDev=pow(sigma2/n,1/2); is the same as either strDev=pow(sigma2/n,0); strDev=1.0; Think about …

StuXYZ 731 Practically a Master Poster

Actually, if you are doing a binary search, make 100% certain that you understand the algorithm in 1D. That is important since 2D array can be easily thougth of as a 1D array. The binary search can be done recursively
but let us start with the simple 1d binary search.

It REALLY helps to do this on paper with three coloured counters that you place on the number the index points to.

consider a set of numbers that are ordered, for simpicity consider
0-99. in linear order.

Now set target = 43  (anynumber between 0-99 will do)
        set first =0 
        set last = 99
        set mid = (first+last)/2 = 49 (remember integer arithmatic)
        
// Loop over
            while(mid!=target)
               {
                  if (mid>target)      // obviously last>mid and it is also LOTs 
                     last=mid;          // bigger than target
                  else  
                      first=mid;
                  mid=(first+last)/2
              }

Understand how THIS works.

Now continue to see that if you have an ordered array of 100 points.
Then first,mid,last represent the array index and the values in the array are only used in the test to see if array[mid]>target.

This is only a fraction away from a 2D array, and slight modifications away from a recursive function.

StuXYZ 731 Practically a Master Poster

Note 100% certain I follow what you are trying to do.
But some points:

(a) C++ is almost space insensitive. The only areas you have to worry are in the middle of keywords e.g. cla ss A { } is not acceptable, nor in the middle of stuff like operator<< e.g. std::cout< <"Hello"<<std::endl; (b) Consider your code:

if(first <= last)
{
int mid = (first + last) / 2;
}

This creates a variable mid. BUT mid has scope ONLY within the braces
e.g. only for ONE line of code. Therefore this if and the creation of mid is useless.

Then you try to use a mid LATER but that does't exist so you get errors.

(c) you pass values into your function e.g. first and last, but immediately you assign them to some value from your matrix. This negates the purpose of calling them into the function.

if(key == Values[][mid])

This line does not work since you have to define the first array index.

Please start with something a lot simpler, try just printing the array, then swapping it around. Doing stuff in stages is often quicker than doing the problem in hand.

StuXYZ 731 Practically a Master Poster

Can you post your new non-compiling/non-running code please.

The only thing that I can think you might have done wrong is to forget to at const to both the declaration and the instance eg.

class A
{
    std::string print() const ; 
};

std::string
A::print() const
{
   std::string output;
    std::list<int>::const_iterator iterI;
  //...
   return output;
}
StuXYZ 731 Practically a Master Poster

This is simple (I hope). You are using an iterator. The iterator allows the method to change the data.

Now since an iterator is a class and your compiler cannot know until link time that the iterator does not change the data, you compiler HAS to assume that the iterator does, hence it doesn't allow const to be added to print.


A simple way to get round this is to use const_iteraror.

Another way is this

std::string
A::print() const
{
   std::ostringstream oSS;
   copy(number.begin(),number.end(),
          std::ostream_iterator<int>(oSS,""));
    return oSS.str();
}

The later method avoids the convert to S construction that creates a number of stringstreams, and avoids having an explicit iterator. So is slightly more preferable to some peoples tastes.

Note: you have to add #include <iterator> , to your C++ file.

StuXYZ 731 Practically a Master Poster

Let me just add, since i is declared as a double , your loops are complete and test with i==1000 are complete junk.

If you add 1 to a double at about 1e16 this is true:

// True on some machine and about this value
double m=1e16;
if (m==m+1)
   std::cout<<"m+1 == m"<<std::endl;

Thus your inner loop will never exit.

StuXYZ 731 Practically a Master Poster

A multitude of errors, mostly caused by trying to write everything in on go.

(a) Patient includes an instance to Doctor. Therefore you must have a declaration of Doctor before Patient is declared. If it was just a reference or pointer you could have used a forward declaration e.g class Doctor; BUT you can't in this instance.

(b) Lots of typos. you use doc to mean doctor etc e.g. in the copy constructor for Patient. You write doctor1() in the main() { } section.

(c) Failure to call the base constructor in derived constructors and in the assignment operator.

(d) Lots of inconsitancy in format/layout which itself is not wrong but makes it difficult to see what is going on. For beginners I would recommend:
(i) Never use using namespace std; (ii) Don't put names of variables within declarations.
(iii) Consistent set/get naming so it is clear
(iv) copy Constructors are build like this e.g.

Doctor::Doctor(const Doctor& A) : Person(A),
  hour_fee(A.hour_fee),reg_num(A.reg_num)
{}

and the assignment operator like this

Doctor&
Doctor::Doctor(const Doctor& A)
{
   if (this!=&A)
     {
         Person::operator=(A);
         hour_fee=A.hour_fee;
         reg_num=A.reg_num;
     }
    return *this;
}

(v) Don't use a general protected, if that is what you have then change your model to a pure virtual inheritance.

(vi) Validate input.

esesili commented: it was very helpful +1
StuXYZ 731 Practically a Master Poster

Some comments:

First yes, one of the original ideas was to only write code once. (it was actually discussed in terms of macros but it still holds)

(b) #include <limits> gives the absolute best possible accuracy. This is not normally very useful for these type of problems. For example, you apply some matrix and quaternion rotations to some vectors, and you want to know if any are "equal". This will include several rounding errors, ie several epsilons. Yes you can determine the number, but normally there is an acceptable tolerance, but for say an eigenvector determination, is not really an option to determine the expected epsilon error from first principles, it is better to set a tolerance.

(c) Don't encode your equals in operator== as a class member. The key thing to note is the operator== does not take an additional parameter. It can only be retType operator==(inputType) {const};
were retType is any return type you like and inputType is any
input type you like BUT you only get one!. (const is optional)

Then because equal takes a number of different levels, e.g. at 1% or 0.0001% etc. Dependent on the instance. That also means you don't encode the tolerance as a static class variable. You then have to change it each call (and will forget).

I like the boost form boost::test_tools::close_at_tolerance<TYPE> and
boost::test_tools::percent_tolerance type forms
which are described http://www.boost.org/doc/libs/1_38_0/libs/test/doc/html/utf/testing-tools/floating_point_comparison.html and http://www.boost.org/doc/libs/1_35_0/libs/test/doc/components/test_tools/floating_point_comparison.html. The second reference is the implementation and the first is why …

StuXYZ 731 Practically a Master Poster

I normally think it is better to wrap these kind of fabs() type test
in a testing namespace , that provides a template form like this

namespace Approximate
{
template<typename T>
 bool equal(const T& A, const T& B,const double precision = 1e-4);

template<typename T>
bool notEqual(const T& A,const T& B,const double precision = 1e-4);

// less / greater etc.

}

Then specialize each type specifically. (that allows a 2/3 value comparison for vector, allows stuff like angles to remove the 360 degree phase invarient [e.g. 361 degrees is often the same as 1 degree]. Also for surfaces, it allows opposite normals to be considered the same (if sense doesn't matter).

This namespace then fits nicely into most testing framework, e.g. CppUnit.http://sourceforge.net/projects/cppunit/ and can be extended if you need to test base/derived classes etc.

Then the framework deals with about 95% of the stuff and you don't have to worry about writing another fabs(a-b)>epsilon and you have only done it once. Which was one of Strustrup's original tenants.

Note back: Normally you implement notEqual as !Equal BUT there are exceptions....

StuXYZ 731 Practically a Master Poster

I really don't think that the problem is with string. Examining you code fragment, buffer2 obviously has size (you could test this with a std::cout<<"Length of buffer2 == "<<buffer2.length()<<std::endl; You haven't done something horrible like have your own local version of string ?? and then the horrific using namespace std; that everyone seems to add has caused you some problems. Basically you are going to need to look at your debugger.

StuXYZ 731 Practically a Master Poster

If you don't want to post your code, then maybe a cut down version. But the quickest way to do it yourself is to compile with debug info on and then run and wait till it crashes. The backtrace will tell you what memory component has been corrupted. It may take a little to work out what has actually happened as another array may have over writen it. The debugger can help listing the symbol and memory addresses.

You can also try valgrind. http://valgrind.org. Which finds memory errors/leaks etc. [with a few false positives.] This is also very good at finding array boundary errors.

Typical things you will find are memory that is assigned but not deleted. Memory that is created with new but deleted with free() and vis-vera. Array over runs. e.g

// runtime error
int A[10];
for(int i=0;i<=10;i++)
  A[i]=i;

etc.
Similar things happen in char* because people overwrite the end of the array. If all the warnings are not on then you can do this

// WRONG code:
char *A="Enter key"
std::cout<<"A == "<<A<<std::endl;
std::cin>>A;

This works if the entry is less than 9 characters long.

tux4life commented: Nice post, nice link :) +9
StuXYZ 731 Practically a Master Poster

Several things from your question:

First the string part. You have many options (a) you can indeed use
insert but the method requires an iterator to define the position for insertion. (b) the easiest to use simply += e.g

char p='x';
std::string A("test");
A+=x;
// A is now testx

Second :note your mistake in your function, you have used pl[0]
but it is a simple character. It is not an array.

Third: I don't understand why you have the variable winner. you assign a value to it and then return from the function. The means that the variable is immediately lost.
do this return 'M'; instead.

Also you claim to return an integer from find_player but you return a character. That is acceptable to the compile (with warnings) but unlikely to be the intent. Surely you wanted to return 0 if it is a draw and 1 if player one won and 2 (or maybe -1) if player 2 won.

Also, don't make a string and then compare, just use the individual result. e.g

// after test for p1,p2 only are s,r,p.
if (p1==p2)   // draw 
  return 0;
if (p1=='r')
   return (p2=='p') ? 2 : 1;
// .. etc

you might want a switch statement, you might also use a lookup table etc.

As for production code, I feel that you need a lot more experience getting code to work and compile before you even ask the question. Nobody checks …

StuXYZ 731 Practically a Master Poster

This is C++ not C, so I would have written:

b= -1*static_cast<int>(x)/2;

The main advantage of this is the you have an explicit bracket around the section you are casting and it is a BIG flag that you are changing type. Something that in numerical code is often such a big area of problems that the old (type) casts are often forbidden.

It also avoids nasty stuff when you convert (accidentally) from a pointer to a numeric type. Easily done when you have a long expression with pointers and multiplications.

StuXYZ 731 Practically a Master Poster

Well the problem seems to be that you expect the array to be terminated with a 0 . This is a mess.

What I think you have done is confuse the normal mechanism for strings e.g.

char* X="Fred";   // This gives    
// X[0]=='F' ... X[3]=='d' X[4]==0

with any other type of array.
e.g.

int X[]={1,2,3,4};
// X[3]==4, X[4] is undefined

But you really don't want to be using the last element of a float as a test value. (what would happen if say you used 0 and then one of your numbers was zero). So instead pass the size.

void displayArray( const float *aPtr,const int Size)
{
    for (int i=0;i<Size; i++ )
        cout <<aPtr[i] << endl;
}
StuXYZ 731 Practically a Master Poster

Looks to me that you are not creating an instant of the template class
for <int>.

You have put the link body in a .cpp file. That is perfectly acceptable and good practice if the body is large. BUT you have not created an explicit instance of it.

So add
template class Link<int>;
at the bottom of your Link.cpp and I think that all will be fine.

Note: notice that your second case is actually a declaration to a function that is not used, that returns a Link<int>. Hence it compiles.

StuXYZ 731 Practically a Master Poster

Well depite the fact that this looks awful, you almost definately have a
memory leak. You initialize line to fslen+10, whatever fslen is. Then you do not delete it.

However, as vmanes says, you are not giving us much to go on. I would, at the minimum post the class and related functions

StuXYZ 731 Practically a Master Poster

I think you have made a mistake in your question. If you have
0..25 in your code your compiler will tell you that it is an error.
However, if you are trying to go from a string to a number the simplest way is to use a stringstream.

The problem with

std::istringstream IX;
double x;
IX>>x;

is that as you say 0.. and 34y will work. So you have to do some more work.

You need to (a) determine if the stream is emtpy or (b) determine if the stream's next character is a space (or other suitable separator). Either (a) or (b) would mean an acceptable number had been read.

StuXYZ 731 Practically a Master Poster

Answer is: Start again

You have

while (getline(cin, info) && info != "")
          { if ( isInVec(word[info.length()], info) == false) 
                 word[info.length()].push_back(info); }

Now word starts empty, so IMMEDIATELY, you access work[X]
were X is a large number. Then you push back to that place.
That is memory corruption.

info is a global string : That is horrible info!="" is better as !info.empty() I am not sure what you are tring to achieve but use .at instead of [] for your vector and it will throw exceptions when you make mistakes like above.

StuXYZ 731 Practically a Master Poster

You can't copy it to a set and back again without breaking the order.
Sets store on a compiler defined manor but normally red-black trees.
Hence you will destroy the order.

The easiest way is to copy to another vector sort, unique
and then find the copies.

Another slightly more involved way is to copy to a map in which you have the positions in the vector as the second component. The remove the clashes. Depending on the vector type a hash map may work better.

robotnixon commented: thanks for the help +2
StuXYZ 731 Practically a Master Poster

You don't seem to have posted enough code for anyone to tell but are you using: m_pEcoAreaTeam = new EcoAreaTeam(); and then the class does not have m_pEcoAreaTeam and you have a scope issue??

If the class has m_pEcoAreaTeam check the spelling. And why the use a global m_pEcoAreaTeam or was that just to illistrate ?

StuXYZ 731 Practically a Master Poster

First off, well done for using code tags for your first post.

Second, your error is that you are returning 0 but actually need to return a string.
Try as the last two lines of padBlanks, this:

blank+=string1;
return blank;
StuXYZ 731 Practically a Master Poster

I thinks you just need to add { } round the loop part.
You add up count each time but then only output n at the end.

If you output n for each step of the loop you will get exactly what you want.

StuXYZ 731 Practically a Master Poster

I am a bit lost: You cannot create a class from template parameters that are not known at compile time. For example

template<int N>
class A
{ };

You can't have A<i> and since you will only have created explicit instances. e.g. A<0> , A<1>. You can do dispatch of a known sequence. e.g 1-10 but that is your lot with templates.

As for adding parameters that are deduced at runtime, that is ok
do that dispatch first , then do the class dispatch (via hold).
In that case put the parameters into hold. OR do class then the dispatch on runtime, boost::any is a quick way to impliment that.

StuXYZ 731 Practically a Master Poster

Well first off, I accept that you didn't get any replies at the previous forum, so I will accept that you should re-post. (I might have waited another day or so but that is minor). Given that, I would like to comment on your problem, and actually ask a few quesitons really.

First off: C++ forbids template virtual functions of any sort. You can normally code round that in a slightly ugly way. Several methods around depending on the probelms (many based on encapsulating the function in a template class)

Second: I think that you are trying to do some kind of template dispatch ???? If this is the case then you should look at the boost mpl.

An effective method of doing what I thnk you want is this:

#include <iostream>

class A { public: static void call() { std::cout<<"This is A"<<std::endl;} };
class B { public: static void call() { std::cout<<"This is B"<<std::endl;} };

class Base { public: virtual void go() {std::cout<<"Base"<<std::endl; } };

template<typename T>
class hold : public Base
{
public:
  
  hold() : Base() {}
  void go() { T::call(); }
};


class C 
{
  Base* object;

public:

  C() : object(new hold<A>()) {}

  template<typename T>
  void setHold() { delete object; object=new hold<T>; }
  void go() { object->go(); }
};

int main()
{
  C cobj;
  cobj.go();
  cobj.setHold<B>();
  cobj.go();
  return 0;
}

The above code basically, sets an internal state variable object, that is an effective virtual object. That results in one extra level of …

StuXYZ 731 Practically a Master Poster

errh... sorry Ancient Dragon, but the last line of the file is just "="?
Which was what I was trying to allude to.

The probelm seems to me to be that you read that with a statement while(partin >> charInput >> numInput) Now you get charInput set to "=", which is correct BUT then the program has to get an input into numInput. If the stream is empty then you just wait. So the program just sits. The while loop condition does not get tested because stream::operator<<(int&)
simply never returns.

The better way to do it is to read whole line of input and then divide the line up.

StuXYZ 731 Practically a Master Poster

You have a problem at the last line of your input file.

You read while(partin >> charInput >> numInput) and you have just = on the last line so it reads into charInput and then waits and waits.....

You need to read the char and then the number, and check the status of the file in between.

StuXYZ 731 Practically a Master Poster

well we still can't figure it out since I am certain that most of the members of this forum are not psychic.
You have not posted code that actually compiles, so I cannot guess what your real code does.

HOWEVER: I think it is that you don't match the first line/number and then you have only read in the first number not the whole line.
So you need a

while(displayData.good())
   {
      displayData>>tempData;
      if (tempData == number)
         {
          //stuff
         }
      else
         displayData.ignore(1024,'\n'); 
}
StuXYZ 731 Practically a Master Poster

Sorry the two different names, addTip and addBill was my mistake.
They should be the same. I just wrote it in the message window (not a very good excuse.)

Your problem is that you really haven't written a simple class yet and played with numbers.

consider

Tips(){  double taxRate = 6.5;  }

That does NOT set taxRate. It creates a local variable and then promptly gets rid of it.
So let use consider a simple class. Because without doing this you are never going to get you code correct.

class A
{
     int X;
 public:
     A() : X(11) {}       // set X to 11
     A(const int Y) { X=Y+21; }
     
     void setX(const int Z) { int X=Z; } // THIS DOES NOT SET X
     void setXReally(const int Z) { X=Z; } // THIS DOES SET X  
     void write() const { std::cout<<"X == "<<X<<std::endl; }

};

int main()
{
   A a1;
   a1.write();
   A a2(43);
   a2.write()
   a2.setX(432);
   a2.write();
   a2.setXReally(432);
   a2.write();
}

Now please go and EXPERIMENT with that code until you understand what it does.

p.s. you have to add standard headers. iostream etc.

StuXYZ 731 Practically a Master Poster

No:

The question what is tempData, was because it is declared string but you are comparing it with an integer.

What you have posted DOES NOT COMPILE, hence we can't debug it. What you have to do is POST code that compiles UNLESS you can't get it to compile and THEN post the error message that is causing the problem.

So does userInformation get opened.... I will repeat ADD

if (disPlayData2.good()) 
  { std::cout<<"My file opened"<<std::endl;}
else
   { std::cout<<"File not found/opened."<<std::endl;}
StuXYZ 731 Practically a Master Poster

Ok the usual rant: I hate system("PAUSE") and CLS. They are non-portable, and I can clear my own screen if that is what I want!

Beyond that you haven't given us much to go on.
You don't test if displayData2 is successful? Does "userInformation.database.txt" exist / get opened, have Windows throw a fit about two dots in the name ?
Use if (disPlayData2.good()) to find out.

Then the lines

while (displayData2 >> tempData)
      {
	<< number <<"\n";

do not compile. Did you mean to pass the number to std::cout, and what is tempData??

You need something like

class userInfoRecord
{
   //stuff
};

std::istream&
operator>>(std::istream&,userInfoRecord&);

and then
tempData should be a userInfoRecord and your test should be if (tempData.getNumber()==number)

StuXYZ 731 Practically a Master Poster

Let me just check, I am seeing goto in a program that you want to submit for marking. The only time I have ever seen that was a stunningly bright student in an advanced class showing how scheme could be used to optimize a mathematical C++ program -- and he wrote about 500 words to justify it.

Anyway the error is highighted by Comatose but in the most obtuse way possible. It is actually that you use a global variable int i, rather than for(int i=0;i<number;i++) and then proceed to have TWO loops one in the other that both use i.
Starting from your code line 122, and continuing

for(i=0;i<number;i++)
{
// Your stuff....
 grade[count].aveex=grade[count].exam/totex*50+50;
      for(i=0;i<=number;i++)
      {
	 grade[count].aveq[i]=grade[count].quiz[i]/totq[i]*50+50;
	 grade[count].totaveq+=grade[count].aveq[i];
      }
//more of your stuff
}

Note that i as ALWAYS number at line 10, and your outer loop can only run once.

I think that you have the closure of the loop in the wrong place, but the code is so platform dependent (clrsrn / delay and such) that I simply can't be bothered to run it.

You can also avoid the problem by writing for(int i=0;i<=number;i++) on line 143 BUT again you really don't want i to get to number since you will have an array error.

In short the code is a mess and you have made a mistake by using a variable in too large a scope (i is in ALL of addrecord) when it should only be in the loops …

StuXYZ 731 Practically a Master Poster

Returning to the problem asked:

The problem is that you have created a class that does nothing.
If you take the trouble to create a class don't ignore the values.
You can put tar=100000; and it will make ABSOLUTE NO difference to the code. I think you have confused yourself by using tar in the class AND tar in the function calculate tip. These are DIFFERENT varaibles

What you might like to do:

class Tip
 {
    private:

        const double taxRate;
        double totalTips;
        double totalBill;
   public:
       Tip(const double TR) : taxRate((TR>=0.0) ? TR : 6.50) {}

       void addBill(const double,const double);
};

void Tip::addTip(const double bill,const double tipRate)
{
  //Your code here -- check for 
  totatBill+=bill;
  totalTips+= // your code;
}

also you might like to note that (for a taxRate in percentage) tax=bill*taxRate/100.0; Finally, money is calculated to the nearest cent/penny, and some care is needed about double giving you 0.3333 etc.

StuXYZ 731 Practically a Master Poster

If a non-static variable is required, it is either local to the method or local to the class. Fine, no problem 99% of variables are just that.

But when a static variable is required, then that is completely different. This way ALL calls to the method regardless of instance have the same static variable. That is typical for specialization of event type in a monte-carlo, base-class has getCell and specialization class knows about the event that can take place, the new energy/velocity of the particle.

StuXYZ 731 Practically a Master Poster

I don't agree. I think that they have a place in modern code.
I have a few situtation that I think merit them. (as will all good things, go easy on them, even in my biggest code bases, there may only be 10 of them).

Let us consider a function in a geometric matrix class, that say gets a point P and finds the appropiate cell which P exists in, and returns that integer.

That function requires a bit of optimization (particularly for non-orthoganal/non-space-filling cells) and it is found that about 50% of the time the cell is the same as the last search. (P didn't move much). So add a static variable to the method, and record the cell found.

Why not add it as a class static variable? Well that adds a level of scope pollution. Why have a variable in the class, and have to have initializers etc, have someone inadvertently change it. It is a similar argument to declaring variables local to the method, in the class.
you simple would not do it, so I don't see how it is different for a static variable.

I fully agree that if the optimization starts getting a bit more sophisticated, the static variable might need to go to the class level, or be registered to an instance of the class etc, or become a complex monster :)

I also like them when some resource is required on something since the static …

StuXYZ 731 Practically a Master Poster

Please do us all a favour and don't double post on multiple forums
E.g.

http://www.codeguru.com/forum/showthread.php?threadid=469551

You were shown short shrift there, because you code is absolutely awful, and you didn't follow their forum rules either.

In addition you didn't take the time to read ANY of this forums rules.

Putting Richard Chaaya's name on the post wasn't to clever either.

Salem commented: *agrees* +27
Comatose commented: *also agrees* +9
Ancient Dragon commented: Awesume answer +36
StuXYZ 731 Practically a Master Poster

By the looks of things (I am guessing a bit -- but there is very little code to go on) , you have a rectangle of with top/bottom cordinates.

Then you add 1 to top and bottom but if you reach the bottom of the screen the bottom only is reset. I guess that you draw with a routine that probabily use the top + size so it doesn't work.

Maybe this will work:

if (KEY_DOWN(VK_DOWN))
{
    d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
   if (rect2.bottom<SCREEN_HEIGHT-1)
      { 
         rect2.top = rect2.top + 1;
         rect2.bottom = rect2.bottom + 1;
      }
}
StuXYZ 731 Practically a Master Poster

Assuming that the FIRST warning/error from g++ is

./../frontends/include/../../frontends/include/../../libdatastore/include/../../libtimetable/include/../../libtimetable/include/Course.h:26: error: ISO C++ forbids declaration of ‘list’ with no type

Then you error is going to be that from gcc-4.0 and onwards, namespace std is not included in the files like list etc.

ie. You write this

#include <list>

class A
{
   private:

    list<int> Items;
  // other stuff
};

and it is going to fail.

you have two quick options write using namespace std; or change the code to std::list<inst> .

I strongly advocate the latter but if your pushed for time try the first.

NOTE: If you add using namespace std; be very careful that you don't do this:

#include <list>
#include "MyClass.h"

using namespace std;

// other stuff.

Note that the using namespace std, needs to be about the include files or in the include files.

StuXYZ 731 Practically a Master Poster

Error on conversion:

Sorry classic error:

int a=9;
int b=5;
 // this gives 1
std::cout<<"Int division "<<a/b<<std::end;

The code you have written gives the error because of 9/5 == 1.
If you write 9.0/5.0 or even 9*(temp-32)/5 you would have the correct answer.

[p.s. Sorry Salem was quicker to posting than me (and he correctly predicted the answer as well!)]

StuXYZ 731 Practically a Master Poster

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?

StuXYZ 731 Practically a Master Poster

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.

StuXYZ 731 Practically a Master Poster

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.

StuXYZ 731 Practically a Master Poster

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.

StuXYZ 731 Practically a Master Poster

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 …

arun_lisieux commented: Very patient and helps out well. +1
StuXYZ 731 Practically a Master Poster

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).