Banfa 597 Posting Pro Featured Poster
Banfa 597 Posting Pro Featured Poster

atoi() returns 0 on error. strtol() is the same function but converts it to long int.

If the text length is greater than 1 and the output is 0, that would indicate an error. Unless someone really wanted to put 000 in there or something.

Using stringstream to cast to int will also fail with output of 0 if the characters are not digits. Admittedly, stringstream is the more C++ way to do it.

You have answered your own question atoi does not return 0 on error 0 is returned for a number of reasons so a 0 return does not equate to a definite error.

strtol is not the same function because it returns a pointer to where the conversion finished so you can easily tell if the conversion finished because it reached the end of the string, white space or an invalid character. Also strtol will handle bases other than 10 which atoi wont but that isn't really relevant here.

Using stringstream with fail with the failbit set if the input characters are not digits. You can not use the output value of convert to integer as a test for success because there are no invalid output values.

Banfa 597 Posting Pro Featured Poster

atoi() is unlikely to help because it has no error output, you could use strtol() however neither of those are C++ they are part of the C standard library and C++ provides the same functionality through the use of stringstreams.

Banfa 597 Posting Pro Featured Poster

If they have input only integer data then all there should be is a string of digits.

  1. So get you get a line of input

  2. Extract an integer from it
  3. Verify the rest of the line is blank

If either step 2 fails or the rest of the line is not blank at step 3 then you have an input error.

You can use getline for step 1 and then a stringstream for steps 2 and 3.

Banfa 597 Posting Pro Featured Poster

Look I know that GNU gcc can produce dependencies and I know that some third party make engines can produce dependencies but as I said I do not believe Microsofts nmake can produce dependencies, in fact as a make engine it is somewhat feature poor.

You keep saying that you want automatic creation of dependencies but I answered that with my first post, nmake does not do that and I am not aware of any tool in the Microsoft tool chain that does except using their IDE which if you are using nmake you are clearly no doing.

Banfa 597 Posting Pro Featured Poster

This discussion has been moved from http://www.daniweb.com/forums/thread284115.html. Check there for the beginning.

= = = = = = = = = = = = = = = = = = = =

Actually neither approach is wrong.

The original code does not store prime numbers but does correctly identify all prime numbers although it does test some values such as 9 that are not required.

The approach suggested by 0x69 requires that you have already found all the prime numbers <= sqrt(userInput). This value is limited by the sizeof int so it is feasible to store all the require prime numbers in an array to facilitate factorisation.

The original code uses less memory but takes more processing (because it tests numbers that are not prime so can be part of the result), 0x69 solution takes less processing but takes more memory (on a 32 bit system enough to hold about 726800 prime numbers) because you have to store that table of prime factors.

So its a trade off, do you want to use an algorithm that uses less processing or one that uses less memory. And you can only really answer that question once you have decided what platform you will be running on and the limits of the algorithm you are writing (perhaps you only need to factorise numbers up to 500, that would reduce the memory requirement quite a bit).

However as I originally said neither algorithm is wrong it …

tux4life commented: Solid advice :) +8
0x69 commented: most neutral explanation here :-) +1
kvprajapati commented: N/A +9
Banfa 597 Posting Pro Featured Poster

You shouldn't just output rgValue, it is binary data unless Type has a value of REG_EXPAND_SZ, REG_MULTI_SZ, REG_SZ.

If the value in the registry is really a DWORD then Type should be REG_DWORD and size1 should be 4 on exit. In that case something (non-portable) like DWORD dwValue = *((DWORD*)rgValue); should do the trick. Alternatively just pass a pointer to a DWORD into RegQueryValueEx in the first place if you are sure of the type the key holds.

RTFM: RegQueryValueEx

freemanirl commented: Yes! +0
Banfa 597 Posting Pro Featured Poster

I have a suspicion that one of the problems is that the Post width has actually been made too large. When reading text the human eye can only go down the page so fast as you scan from the end of one line to the start of the next. This means that for very long lines of text you need extra space between the line or your eye overshoots the line. In the worst case you actually skip lines.

I don't think that Daniweb is at this worst case but I do think that the post lines are so long that the eye overshoots and has to correct upwards when it reaches the beginning of a new line making reading a strain.

This can be tested as currently Daniweb can be shrunk until it is about 930px wide by adjusting browser width (my screen res is 1280 x 1024) and at that width it seems to me that reading Daniweb gets easier on the eye.

On the old site that big margin for the side bar had the effect of doing this for you.

Tekmaven commented: This is a great point. You should be a usability expert! +0
Banfa 597 Posting Pro Featured Poster

If you have ever used Excel with formulas in 1000s of cells then you would know that recalculation is very time consuming. In fact I had a sheet that had a few 100,000 cells filled in and I found that the best solution was to switch off automatic calculation and do a manual recalculate when I had finished all edits.

My point is recalculating everything is a brute force method but is quite common. You could try having each cell knowing what cells it is dependent on and only recalculating cells effected by the original change and any further changes that produces but you have to be careful, it is easy to get into an infinite loop that way if you have a circular dependency of cells.

You might try looking up the Observer Design pattern which might be of assistance.

Banfa 597 Posting Pro Featured Poster

It should never be considered "safe" to cast away a const, on some platforms const values are actually stored in constant unchangeable memory and trying to alter such a value can produce a processor trap. In fact I can not think of a time when casting away the cost is safe.

If you want to alter the value returned then take a copy of it and alter your copy. This is in fact what your code does since you have declare Bar P rather than Bar& P . You can always copy from a const because (generally) copying a value does not alter it.

Banfa 597 Posting Pro Featured Poster

I see nothing wrong with it particularly so you are going to have to tell us what you want it to do and what it actually does since we have no knowledge of its indented purpose.

Banfa 597 Posting Pro Featured Poster

for (j=0;j<2;i++) 3rd expression increment j not i

also you have mismatched braces countof { != countof }

Banfa 597 Posting Pro Featured Poster

Opps missed your comment another reason to post the entire message.

What are you doing trying to open and close an already open stream? out is a working output stream just use it.

Banfa 597 Posting Pro Featured Poster

Windows has no synchronisation exception, nor have I every seen an OS that did.

If you share any data between 2 threads, including an std::string without guarding access to the data then you risk corrupting the data by simultaneous access which is likely to be bad for program execution.

I think you should probably expect an stl::container to throw any standard exception I do not think it is specified what they do and don't throw, probably because of the possibility of it being platform dependent.

Banfa 597 Posting Pro Featured Poster

In my opinion you are making things overly complex and attempting to introducing a style that is likely to just confuse anyone else trying to use the code you write which ultimately results in more maintenance overhead for no actual gain in functionality over

#include <iostream>

using namespace std;

class C_User
{
	public:
		long	getNumber( void );
		void	setNumber( void );

	private:
		long m_iNumber;
};

long C_User::getNumber( void )
{
	return m_iNumber;
}

void C_User::setNumber( void )
{
	cout << "Enter a number: ";
	cin >> m_iNumber;
}

int main( int argc, char* args[] )
{
	C_User User;
	
	User.setNumber();
	
	cout << "You entered: " << User.getNumber() << endl;
	
	return EXIT_SUCCESS;
}

If you wanted to do this you would have to do something even more obfuscating like store a reference to the parent object in _Get and _Set and initialise them in the _Get and _Set constructors when a C_User object is constructed and use the reference to access the parent object data inside the methods of _Get and _Set.

It makes sense that you can not directly access the parent object data inside _Get and _Set methods because inside those methods this refers to _Get and _Set instances respectively and not the parent class instance.

Banfa 597 Posting Pro Featured Poster

When you instantiate a derived class before calling the constructor of the derived class (TwoDayPackage) it calls the constructor of the parent class (Package). Unless otherwise told it calls the default constructor so

TwoDayPackage::TwoDayPackage(const string &sn, const string &saddress, const string &scity, const string &sstate, int szipcode, const string &rname, const string &raddress, const string &rcity, const string &rstate, int rzipcode, double wt, double shipCost, double f)
{
        setSenderName(sn);
        setSenderAddress (saddress);
        setSenderCity(scity);
        setSenderState(sstate);
        setSenderZIP (szipcode);
        setRecipientName(rname);
        setRecipientAddress(raddress);
        setRecipientCity(rcity);
        setRecipientState(rstate);
        setRecipientZIP(rzipcode);
        setWeight(wt);
        setCostPerOunce(shipCost);
        setFlatfee(f);
}

is equivalent to

TwoDayPackage::TwoDayPackage(const string &sn, const string &saddress, const string &scity, const string &sstate, int szipcode, const string &rname, const string &raddress, const string &rcity, const string &rstate, int rzipcode, double wt, double shipCost, double f)
: Package()
{
        setSenderName(sn);
        setSenderAddress (saddress);
        setSenderCity(scity);
        setSenderState(sstate);
        setSenderZIP (szipcode);
        setRecipientName(rname);
        setRecipientAddress(raddress);
        setRecipientCity(rcity);
        setRecipientState(rstate);
        setRecipientZIP(rzipcode);
        setWeight(wt);
        setCostPerOunce(shipCost);
        setFlatfee(f);
}

However Package has no default constructor, either you have to create a default constructor for the parent class or, and this is what I think you need to do, you put in a specific call to a non default constructor.

Additionally your derived class should not initialise/assign the members of the parent class and the parent class constructor should do that (unless it needs to override some values) so your derived constructor should be

TwoDayPackage::TwoDayPackage(const string &sn, const string &saddress, const string &scity, const string &sstate, int szipcode, const string &rname, const string &raddress, const string &rcity, const string &rstate, int rzipcode, double wt, double shipCost, …
FlynnLags commented: Helpful and solved my issue +0
Banfa 597 Posting Pro Featured Poster

stdlib.h is one of the C standard headers and contains quite a large and varied number of function declarations, the exact contents you can easily google.

If you call a function without having first declared or defined it when it is defined somewhere in your program then in C you will get an "implicit declaration of function" warning because when the compiler sees the function call it implicitly declares the function as returning int.

#include <stdlib.h> fixes this for any functions that it contains the declarations for because if you included it then you have declared those functions so no implicit declaration happens.

You should usw #include <stdlib.h> anytime you want to call a function that it contains the declaration for.

Salem commented: Nice +20
Banfa 597 Posting Pro Featured Poster

You are more likely to get your questions answered if you actually post them.

Banfa 597 Posting Pro Featured Poster

Mixing cout and printf to output your results is a mistake.

That 4 being output is the return value of printf, it printed 4 characters.

Get rid of the printf and instead pipe count[c] staight to cout in the normal way. If you want to format the output read up on the io manipulators found in the header <iomanip>

Banfa 597 Posting Pro Featured Poster

Just a couple of notes on how you have implemented your operators. Taking operator+ and operator+= as the examples but it applies to all the other ones too.

Firstly because operator+= does in place addition it can return const Number& rather than Number which is more efficient as there is no object copy on return. Note that operator+ must return Number on the whole to work properly but that may involve copying objects (calling copy constructor and destructor) so is less efficient.

So you have implemented operator+ and implemented operator+= in terms of operator+. That's ok but consider this code

Number result, num;
int i;

// Initialise i and num

num += i;
result = num + i;
result = i + num;

Line 8 will not compile with your object.

Now instead lets pretend that you actually implemented the addition algorithm in operator+= you can write operator+ as member function like this

Number Number::operator+(const Number& number) const
{
    return Number(*this) += number;
}

This form has the advantage that a good optomising compiler can perform the return value optimisation. This optimisation removes the copy of the returned objected in some cases by constructing the return value directly in the place it is being returned to.

Better we can write the operator+ that take differently typed values as helper functions, they don't even need to be friends as they only call the public interface of Number, that allows us to write


       
jonsca commented: Good explanation +4
Banfa 597 Posting Pro Featured Poster

hi thank you very much for your help
but am a bit lost can you show me in the code please??

Not unless you show that you have some understanding of what it is you are actually trying to achieve because then I would just be doing your work for you.

You might want to start by forgetting about coding and actually doing the exercise yourself. Choose N, 4 or 5 would be good numbers, then construct the triangle yourself from spaces and stars.

Note carefully how many spaces and stars are on each line and compare that to the line number. From that build up a method of constructing each line given the value of N. Once you have done that you may be ready to start writing a computer program to implement that algorithm.


I will say that what I should have said about line 14 is

Line 14 - you use counter without initialising it to anything

which I hope makes more sense.

Banfa 597 Posting Pro Featured Poster

The reason that subject is not covered in any books on C++ is that there is no standard way to draw graphics or play sounds because C++ is a multi-platform language and graphics and sound hardware/drivers are platform specific.

You will need a library but it will have to be a 3rd party library be that QT, wxWidgets, WIN32 API or some other library. You will have to make the decision on which library to use most of the popular ones have fairly good on line documentation and tutorials.

It is not at all easy to write your own graphics and sound library.

Banfa 597 Posting Pro Featured Poster

You don't use the the output from the stringstream sa to resize your query table.

That is what everyone has been saying. Your query table has a fixed size, that is the number of defined questions, 300 from your first post.

You have 2 options either you select question randomly as you ask them. In this case you need a table with an entry for every question (300) which you use to initially mark all questions as unused and as you ask a question you mark it as used so that if it gets selected again then you can make a new selection rather than asking the same question.

Another option is before asking any questions build a list of the question you will ask that references the complete table of questions.

Ignoring possible problems if the number of questions being asked is a large proportion of the number of available questions those 2 different method both require an additional table that is not the query table.

the query table remains a fixed size it is the ancilary tables whose size may alter depending on the method used to record questions asked/to ask.

dualdigger commented: really helpful suggestions +1
Banfa 597 Posting Pro Featured Poster

You will need to change this line as well m_Qtable.resize(m_QNo); as well and in fact you will need to change all instances of m_QNo in your code, both posted and unposted where you have accidentally used the question number rather than the number of available questions as your limit for accessing the question table.

Ancient Dragon commented: Yes, your right. +28
Banfa 597 Posting Pro Featured Poster

Firstly your iterative version is highly in efficient. If you checked a != b between lines 10 and 11 then you could avoid all the loops and other checking when a == b. That is quite a lot of processing because you will cut out 9 * 9 * 9 * 9 = 6591 iterations of themain loop body.

You will need to include more { } pairs to properly block your loops.

Also notice I said 9 * 9 * 9 * 9 not 10 * 10 * 10 * 10? Your algorithm is wrong. Have you checked the output? Not a single number will contain the digit 9 because you have all your loop end condition wrong.

In your recursive version your method to isolate the digits does not work, consider the number 123456 and consider your attempt to isolate the 3rd digit n / 1000. 123456 / 1000 = 123. It clearly doesn't work. You need to use the % operator.

Also you have a while loop in the function. A loop like that in a supposedly recursive function is normally a clear sign of an error. recursion replaces iteration.

A recursive function should have an end condition. If the end condition is met the function returns otherwise the function recurses.

The whole recursion returns a single result. Your cout statement is outside the function in main so if the function was working the program would pront a maximum of 1 …

Banfa 597 Posting Pro Featured Poster
while(fgets(line, 100, file)!=NULL) {       /* keep looping until NULL pointer... */

"I have detected danger Will Robinson"

More specifically I have detected that line was declared char line[20]; so is a 20 byte array but you have passed a pointer to line and told fgets to copy up to 100 characters into it leaving yourself open to a buffer overrun. For safety this should be

while(fgets(line, sizeof line, file)!=NULL) {       /* keep looping until NULL pointer... */

And again

numbers[i]=atoi(line); /* convert string to int */

but numbers is declared double numbers[]={0}; with no array size but an initaliser list with a single entry means that numbers has a size of 1 so as soon as i > 0 you have an out of bounds array access.

Additionally your file appears to contain floating point values and you are using double type to store your converted value but you are calling int atoi ( const char * str ); which returns int and explains many of your conversion errors. You should try calling double atof ( const char * str ); .

To get your numbers array the right size you are going to have to do something using dynamic memory allocation with malloc/realloc.

Salem commented: Yes +20
Banfa 597 Posting Pro Featured Poster

Assume a class declared like this (I have reduce it to 1 float for berevity)

class MyClass
{
public:
    MyClass(float initx);
    setX(float newx);

private:
    float x;
}

You are say since the constructor is implemented as

MyClass::MyClass(float initx)
{
    x = initx;
}

you could just call setX which does the same thing. The mistake is that you are assign in the constructor when it is more preferable to use initialiser lists so you constructor should really be

MyClass::MyClass(float initx)
: x(initx)
{
}

Nothing like setX!

A float is a simple case but get into the habit of using intiialiser lists. You will often want to use them if you have a class hierarchy anyway to initialise base classes in a specific way.

if the constructor calls some code that is also called by a class method then probably the best thing to do is to put the code into a private method that both the constructor and public member call. That is separate the implementation from the interface. Also also allows for such things as differing checks on data validity before calling the common code.

Banfa 597 Posting Pro Featured Poster

Actually this piece of code is not really interested in the sub-class at all. It just needs a Request* in order to queue the request.

It looks like you could use a factory method. A factory method is often a static member of a base class that accepts data and uses the data to create a sub-class of that base but returns a base class pointer.

This keeps the code the knows how and when to create the sub-classes nicely encapsulated in the class your code you then look something like

Request *request=Request::requestFactory(line);

	if (request != NULL)
	{
		requests.enqueue(request);
	}

The factory method looks something like

Request::requestFactory(const QSTring& line)
{
	RequestTypeType requestType = <Decode type From Line>;
	Request* retval = NULL;

	switch(requestType)
	{
	case REQUEST_LOGIN:
		request= new LoginRequest;
		request->tcpMessage=line.toUtf8();
		request->decodeFromTcpMessage();
		break;

	case OTHER_REQUEST_TYPE:
		request= new OtherRequestType;
		request->tcpMessage=line.toUtf8();
		request->decodeFromTcpMessage();
		break;

	...
	}

	return request;
}
metdos commented: Nice, Clean , Informative answer +1
Banfa 597 Posting Pro Featured Poster

You have not fully taken on board the nature of floats (and doubles). it has nothing to do with the machine being 32 bits, it is the nature of how floats hold there values that they are approximations (normally good ones) that is a float is rarely 2.5 or 3.0 it will be 2.499999 or 3.00001 with the possible exception of a float variable immediately following initialisation.

You are multiplying by 100 and then trying to test the remaining decimal places to see if they are 0 and if they are not 0 rounding up. However because of this aprroximate behaviour except for a variable immediately following initialisation so any value that has been calculated you have to assume that the digits following the ones you are interested in are always non-zero.

Even for the simple multiplication * 100. A float may be able to hold 2.500 exactly and it may be able to hold 250.00 exactly but 2.500 * 100.0 could result in 249.99.

So under the assumption that the trailing digits of a floating point variable following some calculations are never 0 and the strict definition of rounding up you will always be rounding up.

In that case you can save yourself the hassle of the calculation, * 100 truncate and + 1.

That is probably not want you want to here but that is the nature of floats.

Your only other option is what you have suggested, choose a tolerance that …

Ancient Dragon commented: very nice :) +27
Banfa 597 Posting Pro Featured Poster

start quote:

main()
{
           int a;
           a=message();
}
message()
{
          printf("\n C language");
}

what is the output and what return will return to a;

Since this is the C++ forum there would be no output from that since C++ does not support implicit types on functions or calling functions without a prototype so the code will not compile.

Assuming that you meant to compile it as C and that you are willing to ignore the warnings produced rather than fix them then the output of the code is either undefined behaviour or extremely platform defined.

WaltP commented: Another 3 year resurrection... +11
Banfa 597 Posting Pro Featured Poster
char *myChar = const_cast <char*> strMyString.c_str ();

In general this is a bad idea, c_str returns const because you should not be changing the data pointed to by its return value. Randomly casting away the constness for no good reason is asking for trouble and undefined behaviour.

cstr = new char [dir.size()+1];
		cstr2 = new char [dir2.size()+1];

		CopyFile(cstr, cstr2, false);

This just creates 2 buffers of the right size without putting anything in them and then passes the unitialised buffers to CopyFile.

You need to see everyone elses comments of string::c_str you may just want to consider looking the method up in your reference material.

tux4life commented: Solid advice :) +8
Banfa 597 Posting Pro Featured Poster

main returns int not void (although that isn't actually causing the error it is quite a serious mistake).

You define infile on both lines 47 and 68. You can only define a variable once in a single code block. You need to either

re-use infile rather than redefining it or use a different variable or (my favourite) split you program up into sensibly sized functions isolating bits of functionality, such as loading 2 files, from each other.

Banfa 597 Posting Pro Featured Poster

operator+= is the in place addition operator. That is it alters the object it is called on, unlike the binary additional operator operator+ which does not alter the object it is called on at all but just returns a new result.

Your impletemtation is not in place, that is it does not alter the object it is called on,it creates a new temporary object temp and alters that.

They way you have written it x += y does not alter x which is what you are seeing. If you wrote z = (x += y) with your current implementation then you would find that x was unaltered by z had the sum of x and y.

You need to re-write your operator+= so that is does an in place calculation, that is so that the object that it is called on is altered to contain the new value. You will not need the variable temp at all in such an implementation.

Banfa 597 Posting Pro Featured Poster

Yep that would be my opinion, don't bind anything let the operating system make its own decision.

A lot of relatively brilliant minds have gone into writing the algorithms that the processor uses to decide which thread/process to run on which core. Supposing you can make a better decision is at best foolish.

You try and run many programs that all suppose they can do the binding better and circumvent the processors own routines and you are likely to tie the processor up in knots and prevent it working at all efficiently.

jonsca commented: Wise +4
Banfa 597 Posting Pro Featured Poster

A quick Google produces http://gcc.gnu.org/onlinedocs/gccint/Collect2.html

So the answer (reading that) is no collect2 invokes your linker for you but might well be the program you run when you execute ld.

Everything wraps something else which comes back to my point of why make things complicated trying to invoke ld yourself when you can invoke it through gcc and take the complications out of it. Producing good programs is more than hard enough without setting yourself extra challenges especially when anything you learn doing this will stop applying the moment you start using a different tool chain.

Also note in post #6 I said to invoke gcc on objects not on C files as you implied in post #8.

Salem commented: Nicely put +20
Banfa 597 Posting Pro Featured Poster

@prushik

You may well find it easier, initially to link through gcc (or g++) Both of these programs are really entry points onto the entire tool chain rather than actual compilers which is why you have to issue them the -c switch to make the only compile. Similarly to can get then to just link by simple putting obejct files on there command line try gcc hello.o -o hello .

Calling through the entry point like this helps because it automatically adds things that are normally the same every time. you can call ld directly if you want but in my opinion it is only worth doing if you really need to call ld in a way that is different to how gcc calls it.


BTW what hasn't been said yet is that for embedded programming there is often (sometimes) a third step after linking as follows

compile
link
locate

Generally all platforms require you compile and link but linking tends to produce a relocatable executable image, that is an executable image that can be run from any memory location. For some embedded platforms they are expecting the image to be in a specific place in platform memory and the program loader is expecting the image to know where it is supposed to be located.

On platforms like this you run the relocatable image through a locator to produce an executable image for a specific location in memory.

Like …

Banfa 597 Posting Pro Featured Poster

no you can't my compiler produces this error

bytes.cpp:8: error: ISO C++ forbids variable-size array `a'

Variable size arrays are not part of C++ (they are a part of C99) if your compiler allows that code in C++ then it is using an extension to the standard.

In standard C++ you have to do it by allocating (new) the array once you know the size and deleting it afterwards.

#include <iostream>
using namespace std;

int main()
{
	int x;
	cin>>x;
	int* a = new int[x];
	for(int i = 0;i<x;i++)
	{
		cin>>a[i];
		cout<<"\n"<<a[i];
	}
	
	delete[] a;
	return 0;
}
gaya88 commented: thanks +0
Banfa 597 Posting Pro Featured Poster

Sorry I thought that was a very accurate answer to the actual question you posted. Perhaps you should try doing your own homework and then asking more explicit questions if you run into trouble.

I for one am not going to be writing your homework assignment for you and I doubt anyone else here will either.

Here are a few hints

  • You are going to need to check every element in the array so some sort of loop will probably be required

  • You are looking for the largest value so you will need to be doing some comparisons, that means if statements and compaison operators
  • You are looking for more than 1 result so you will possibly require an array to store the results in.
  • To make things simple start by writing a program that just finds the largest value in an array, then once it is working modify it to actually work out the indexes in the array that the value is stored at.

If you only have 10 hours to complete it you better get cracking!

Next time please don't PM me.

Banfa 597 Posting Pro Featured Poster

No there is a way to get the square root of a negative number but as Ancient Dragon says the result is imaginary.

The square root of -1, sqrt(-1) is assigned a special value by mathematicians, i (engineers tend to use j for the same value). You can not actually write a value down for i as you can other constants like PI for instance (3.141...) i is the imaginary number that satisfies the equation

i x i = -1 (i squared equals minus one)

By having i the square root of negative numbers can be calculated because

-624.5 = -1 x 624.5

so

sqrt(-624.5) = sqrt(-1) x sqrt(624.5)

sqrt(-1) = i and we can calculate sqrt(624.5) because it is positive therefore

sqrt(-624.5) = i x sqrt(624.5) = 24.99i

If you square the result you get -624.5 showing that this is the correct square root.

Ancient Dragon commented: good answer :) +27
Banfa 597 Posting Pro Featured Poster
// Are we painting an edit control?
  if(nCtlColor == CTLCOLOR_EDIT)
  {
    // Yes ...
    // Set the text color to red
    pDC->SetTextColor(RGB(255, 0, 0));
    ...
  }

MSDN also says

To change the background color of a single-line edit control, set the brush handle in both the CTLCOLOR_EDIT and CTLCOLOR_MSGBOX message codes, and call the CDC::SetBkColor function in response to the CTLCOLOR_EDIT code.

so that if statment should be a little more complex (or have further else if clauses.

@mrnobody all of those if statements contain the same block of code so I would not do it like that. If you have direct control of the values IDC_EDIT1 - IDC_EDIT200 arrange the values so that you can implement the condition IDC_EDIT1 <= ID <= IDC_EDIT200 or find some other short cut to answer the question, is it one of my edit boxes.

mitrmkar commented: Yes, a good catch +5
Banfa 597 Posting Pro Featured Poster
for (int index = 0; index <= limit - 1; index++)

is a bit awkward with the <= limit -1 . Just use the strictly less than comparison to the actual array size (or limit of valid elements), as in

for ( int index = 0; index <  limit ; index++ )

It is more than a bit awkward I have seen program errors introduced by this <= limit -1 construct that are not possible with < limit .

It needs a slightly different situation but imagine that

  1. index has type unsigned rather than int

  2. limit is not a constant it is a variable of the program which has a value >= 0

I found this exact bug in a digital television receiver where presumably the original coder hadn't thought of the possibility of a channel having no audio streams at all although that is perfectly valid.

So if everything is unsigned and limit is 0 then limit - 1 is a very large number, 0xFFFFFFFF on a 32bit system and suddenly you have an infinite loop.

This error does not happen with < limit

vmanes commented: Very interesting observation. +5
Banfa 597 Posting Pro Featured Poster

Interestingly if you had bothered to read the text of that page below the Java applet it tells you exactly how you can calculate the interior angle for a regular polygon and further it links boldly at the top of the page to a page about exterior angles too.

Salem commented: LOL +19
Banfa 597 Posting Pro Featured Poster

But I am not using any objects.

It's an ambiguous use of the term object (that we all do).

In an object orientated programming sense an object is an instantiation of a class. However in the context of any executable code an object is any thing that takes up space in memory such as a char array.

Ancient Dragon commented: good point. +27
Banfa 597 Posting Pro Featured Poster

When you declare a data member static there is a single copy of that data member used by all instances of the class so a.n and CDummy::n refer to the same variable.

CDummy::n is incremented every time a class is constructed and decremented when the class is destroyed. So the first cout 7 classes have been created, a, the 5 in the array b and the one newed that c points to, the constructor has been called 7 times and CDummy::n incremented 7 times from 0 to 7.

The c is deleted, the destructor is called and n is decremented so at the next cout CDummy::n has a value of 6 (7 - 1).

PDB1982 commented: Excellent explanation - Thank you! +1
Banfa 597 Posting Pro Featured Poster

start by reading this and relevant pages it links to.

The basic purpose of an assignment operator is to copy all the data from the source object into the current(target) object making sure, if necessary, that buffers are allocated as required if the class uses pointers to allocated data rather than only uses data types (which you class doesn't I believe).

jonsca commented: Rep for this monster thread +3
Banfa 597 Posting Pro Featured Poster

i already have my program to check that the input number is prime or not and your program is for the specific number while i want to calculate first 20 primes.
and here is what i've made but it is not working,

int main(void)
{
int a,b,c;
for (a=1;a<21;a++)
{
for (b=21;b>2;b--)
if (b<a)
{
c=a%b;
if (c==0)
break;
else
printf ("%d",a);
}
}
getche ();
}

You want to print the prime numbers, however the test for primality is not divisible by any integer less than itself except 1. That means you have to check every single integer (not true actually but in your simplistic algorithm it is) before you can be sure a number is prime. That means your print statement must be outside the inner loop and when you have exited that loop you need to be able to tell if the loop completed or if the break happened. If the break happened the number is not prime.

Also note your end condition for inner loop is wrong, you never check to see if a is divisible by 2. I think you may find that 4 is incorrectly identified as prime.

You say you want the first 20 primes but this actually calculates the number of primes <= 20, there will certainly not be 20 of them. The end condition for the outer loop should be on the number of primes found so far.

Xufyan commented: thankx..xufyan +0
Banfa 597 Posting Pro Featured Poster

The problem is that the parameter number is const (constant) but you are trying to use it to call operator- which is not a const member function. number (const Number &) can not be converted to Number * in order to make the method call in return number.operator -(*this); and you get that error because of it.

However I think you have a more fundamental error because operator+ (and operator-) should not return *this, it should return a new object there should be no in-place alteration of the current object(this) under addition.

For example

int a = 5;
int b = 10;
int c;
c = a + b;

After running this code a = 5, b = 10 and c = 15 but

Number a = 5;
Number b = 10;
Number c;
c = a + b;

After running this code the way you have it written a = 15, b = 10 and c = 15 because Number::operator+ modifies the object it is called on.

Instead of creating operator+ I suggest you create operator+= also you should implement a copy constructor Number::Number(const Number&).

Then you can simply implement operator+ as

Number Number::operator+(const Number& rhs)
{
    return Number(*this) += rhs;
}

implement it inline and if you are lucky you will get a return code optimisation.

Banfa 597 Posting Pro Featured Poster

<pedantic>
Most of the above posts make the following assumptions

  1. 'B' - 'A' == 'C' - 'B' == ... == 'z' - 'y' == 1 and similarly for all letters that are adjacent in the alphabet.

  2. 'a' - 'A' == 'b' - 'B' == ... == 'z' - 'Z' and similarly for all lower case upper case letter pairs in the alphabet.

These relationships between the numeric values of letters are not a function of C (or C++) but rather a function of the execution character set in use, in this case ASCII. The C standard does not require the use of ASCII as the execution character set or in fact any particular character set and does not require the relationships 1 and 2 above. It does require that

'1' - '0' == '2' - '1' == '3' - '2' == '4' - '3' == '5' - '4' ==
'6' - '5' == '7' - '6' == '8' - '7' == '9' - '8' == 1

There are some character sets where the letters do not have contiguous character values EBCDIC is the example normally given where 'J' - 'I' == 8.

While a very large number of today's platforms use ASCII as their compilation and execution character set there are still some platforms (mobile phones spring to mind, or at least the SMS parts of them) that don't.

It is normally easy enough to get round this …

Banfa 597 Posting Pro Featured Poster

Just put an if statement round the contents of the inner loop testing the condition a != b

BTW the is little point doing the calculation for b == 1 because a % 1 == 0 for all a.

Banfa 597 Posting Pro Featured Poster

The problem is that you class Subject has no virtual methods so has no vtable to allow the dynamic cast to happen.

The esiest way to solve this is to add a virtual deestructor virtual ~Subject() {}; to Subject. If you are going to sub-class from it and use base class pointers the destructor should be virtual anyway to ensure correct operation should you delete through the base class pointer.