ohnomis 36 Light Poster

I need to make a servlet that takes in a web page url, cleans up the HTML and spits back out a xml file which i need to make conform to a schema.

This is a class assignment and I have no idea how to go about to doing this. I am supposed to use tagsoup1.2.jar to clean up the html that I pull in have it clean up my html and convert it to xml in the servlet so I can do stuff with it.

Can someone guide me in the right direction? I have no idea where to start. So far, all I've done is made an empty servlet.

ohnomis 36 Light Poster

I have no idea how to reproduce that problem. I can't get your program to work the way you're explaining :(

Did you try installing the program? With this reply, I've included the installer. Just run the installer, next, next, next. Then put this data.csv file (attached with this post), in C:\Program Files\Kotoba (not inside C:\ProgramFiles\Kotoba\KotobaSetup).

Now with the file there, when the program opens, it will auto load the data into the listbox, and when u close the program, it will auto save the data into the same csv file and update it accordingly.

Try searching for one the words without the definition. ie) itai = hurt | In the search box, type in itai and it should highlight (select) itai = hurt in the listbox. Try it with the other strings and it acts funny or will select the wrong item.

Hope this helps clear it up a little.

ohnomis 36 Light Poster

The problem with the search mechanism is that when I search a single word in the "I" category, things get messed up.

For example, when you run the program, enter in some sample words like this:

word = immediate, definition = at this moment // this will search properly because it is a single word lookup (immediate)

however, when you use sentences start with "i xxx xxx" (i space xxx) or "i'm xxx" (i apostrophe xxx), the mechanism gives me random results.

put in these three samples and try to search for them and you will understand what i mean.

Word / Definition
============
immediate / right now
i'm tom / this is tom
i am going crazy / this doesn't sound normal

enter these 3 samples, and try to searching them up. It only happens with the "I" words/definitions for some weird reason, it works for every other letter in the alphabet. really strange.

ohnomis 36 Light Poster

Hi sknake,

Yes, I was looking for some insight if there was maybe a better option than a csv file. I'm still currently a student, so my programming skills are still being worked on. However, I have worked with SQL before and was thinking of doing something along those lines in the future. For now, I just wanted to get something quick and dirty going. I wanted it to be functional before I revised it to an SQL database. I was debating scrapping csv and going xml today. Anyways, you guys can take a look at my code and see whats going on.

Things that are bugged out is basically the search function when I use words that start with the letter I. Single word strings work, but multi-word strings are messed. Multi-word meaning "I am new" or "I'm a person". Anyways, take a look, the installer is also included.

ohnomis 36 Light Poster

Could you please be a bit more elaborate on the code?
What is Word etc.

Well I want to paste the code, but its pretty big. =(

Basically, I have a program that loads up a listbox full of Words.

Words is a class that holds a word and a definition;
ie
Word Object = private string word, definition; + getters/setters.

WordCollection is an a collection that holds a bunch of words.

This collection is the datasource for my listbox.

Is there any specific part of the code you want to see? I can just paste some parts I think that are important.

The import and export code:

private void exportDatabase()
        {
            string path = @"C:\Program Files\Kotoba\data.csv";

            if (File.Exists(path))
            {
                try
                {
                    StreamWriter streamWriter = new StreamWriter(path);

                    foreach (Word wordItem in words)
                    {
                        streamWriter.WriteLine(wordItem.SaveData());
                    }

                    streamWriter.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + "\n");
                }
            }
        }

        private void importDatabase()
        {
            string path = @"C:\Program Files\Kotoba\data.csv";

            if (File.Exists(path))
            {
                try
                {
                    StreamReader streamReader = new StreamReader(path);
                    char[] delims = { ';' }; // for setting delimiters

                    while (streamReader.Peek() > 0) // if item exists
                    {
                        // read in values line by line
                        string line = streamReader.ReadLine();

                        // seperate values into array
                        string[] splitValues = line.Split(delims);

                        // add word to the listbox
                        Word word = new Word(splitValues);
                        words.Add(word);
                    }

                    // sort in alphabetical order
                    words.Sort(delegate(Word x, Word y) { return String.Compare(x.WordInput, y.WordInput); });

                    streamReader.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + …
ohnomis 36 Light Poster

Hello everyone,

I'm having trouble making a search box for my program.

This is a not a school project or anything, just a personal project I've been working on. Therefore, any possible solutions are welcomed.

This is basically a program is a dictionary program of sorts. The user enters in a word and a definition. The word is then stored in a collection (WordCollection), and this collection is the datasource for a listbox control which the user scrolls through to find words/definitions.

The problem I have is not with the program, but the import/export and search functionality within the program.

Right now, I am using .csv format to import/export the file. The exported lines would look something like this:

the garbage people throw out, garbage is waste

The problem is when I have two definitions like this:

i'm a pig, you're not a pig // fails search
i am a pig, you're not a pig // fails search
immediate, right now // works, so I assume there is a problem with space/apostrophe in my search mechanism right now

Here's the code I'm using at the moment.

// sort in alphabetical order
words.Sort(delegate(Word x, Word y) { return String.Compare(x.WordInput, y.WordInput); });

foreach (Word word in words)
{
    if (word.WordInput == txtSearch.Text)
    {
        int index = words.IndexOf(word);

        lstWordList.SetSelected(index, true);

        break; // select the first match
    }
}

Any help or solution would be appreciated.

ohnomis 36 Light Poster

That's what I will do. But it is up to you.

Sounds good, but I at least want to go in with a good argument. Don't feel like upshowing my teacher without having a good basis. =P

Thanks for all your help guys. =)

ohnomis 36 Light Poster

14177 in hex is 0x3761
1982543713 in hex is 0x762B3761
0x61 is lowercase 'a' in the ASCII character set.
0x37 just happens to be the junk in the MSB of the short value.
0x762B just happens to be the junk in the MSW of the long value.

Sorry, but this is only my 4th week into learning C and those concepts seem quite advanced. I haven't learned too much about ASCII and hex. But I'll try to understand from my own knowledge.

Since from your example, it looks like the output is appending junk to the beginning of my 'a' hex value. So this means

a = 0x61
when outputted as a short = a = 0x3761 = the 37 being junk
when outputted as an int = a = 0x762B3761 = 0x762B37 = more junk added to the original junk (37).

Thanks for helping me understand. =)

Now the problem is what do I do, should I just submit it as is and make this argument about the small/big endian and the garbage values and how its impossible to duplicate?

ohnomis 36 Light Poster

no, int the main function you have initialized the char, then the short, then the int, Now if you initialize int or long first and then the short and byte, you will have a well defined behavior, just like the memset that salem suggested. That's what i ment

I see what you mean. If I initialize the l first, then the union is created with 4 bytes and fits all the other data types right? Therefore, you get:

char c = a
short = 97
int = 97
long = 97

The only problem now is that this means nothing in relation to the sample solution provided. =(

When I type in the same input (ie. a, 1, 1, 1)

The result is:
char c = a
short s = 14177
int i = 1982543713
long l = 1982543713

I have no idea what those numbers mean. Like why is the short s = 14177? Why is the int i = 1982543713? Are these just garbage random values generated because the sample prog didn't initialize its variables properly? So I'm sort of chasing an impossible to match answer?

ohnomis 36 Light Poster

Uninitialized data can never ever be trusted. You are bound to get random values immaterial of the compiler you use and the processor you use. As Salem said. And if you have initialized the long int first(in which case all the bytes in the union would have been initialized) you will get the same answer on all computers that you compile the code, provided they all have little endian byte format or if they all have big endian byte format.

What do you mean by initialize the long int first? Do you mean like:

union integer_union
{
    long l = 0;
};

Like initialize it inside the union then use it?

Or maybe

int main()
{
iUnion value;

value.c = 0;
value.s = 0;
value.i = 0;
value.l = 0;

//rest of code
}

ohnomis 36 Light Poster

Maybe

iUnion value;
memset( &value, 0x00, sizeof value );
// rest of code.

Then try 0x55 0xAA and 0xFF in place of 0x00 and test with each of those as well.

These are the results I get:

0x00
---
Please enter a char: a
char c = a
short s = 97
int i = 97
long l = 97

Please enter a short: 1
char c = ☺
short s = 1
int i = 1
long l = 1

Please enter an int: 1
char c = ☺
short s = 1
int i = 1
long l = 1

Please enter a long: 1
char c = ☺
short s = 1
int i = 1
long l = 1

Press any key to continue . . .

0x55
---
Please enter a char: a
char c = a
short s = 21857
int i = 1431655777
long l = 1431655777

Please enter a short: 1
char c = ☺
short s = 1
int i = 1431633921
long l = 1431633921

Please enter an int: 1
char c = ☺
short s = 1
int i = 1
long l = 1

Please enter a long: 1
char c = ☺
short s = …

ohnomis 36 Light Poster

Different compiler, different time of day, who knows.
When you have undefined behaviour (like relying on the contents of uninitialised data), then all bets are OFF!

Your answer will never be the same as theirs except through sheer dumb luck.
If they can't explain that, or mark you down because of it, then you need another teacher.

What if I initialize the data then? Would that make a substantial difference? I thought this program is initializing the data with the user input (ie. scanf("%c", &value.c);). =( I guess its something I don't understand here.

ohnomis 36 Light Poster
void displayUnion( iUnion );

union integer_union
{
      char c;
      short s;
      int i;
      long l;
};

typedef union integer_union iUnion;

int main()
{
      iUnion value;
     
     //code continues

Hey in your program you are declaring a prototype of function display as shown below:

void displayUnion( iUnion );

And passing an argument of type iUnion to it when a union of type iUnion is not even defined.Hence at that point of time it defines the function in some way but not knowing the real structure of iUnion only.

Try this:

union integer_union
{
      char c;
      short s;
      int i;
      long l;
};

typedef union integer_union iUnion;

void displayUnion( iUnion );

int main()
{
      iUnion value;
   
      //code continues

Thanks, I fixed that part. It didn't make a difference though. =P The program still outputs the same results as before.

ohnomis 36 Light Poster

> I don't understand whats wrong with my code.
Part of the problem is that the person who set the homework doesn't know either. You might want to start questioning and verifying what they say from some independent sources.

Both are wrong for exactly the same reason, which is that you have uninitialised data.

I don't suppose your "tutor" has even heard about endian problems. Because that's another thing which would shoot this whole thing down, even if you got everything else right.

I'm not sure if I'm in a position to question the homework. I'm assuming this question has been asked over the years or maybe someone else should be having the same problems. Either way, what basically happens is teachers sample prog output and my output are different. I don't understand why. I don't see anything wrong with my code.

All I'm basically doing is storing a user input into a variable stored inside a union. Then pulling out the value and displaying it as another data type. Which is where some of those garbage values come into play.

ohnomis 36 Light Poster

I don't understand why you expect the same answer.

You are assigning the chat a value 'a', i.e., 97 is stored in the first byte.
Now you are retrieving the value stored in 2 bytes(short), 4 bytes(int and long) so the garbage data will be taken and you are bound to get different values.

The second time the short will get the expected answer since you have assigned it a value, but in the event the char c gets changed to character 1 which is the smiley displayed(See Ascii table) and the int and long will still contain garbage value.

Perhaps you miss understood what union is. Google to know more about it.

Form what I understand, a union is basically a structure that allocates the same space to store its data. So the char, short, int and long variables all share the same storage location (size being that of the largest data type).

I'm only expecting the same answer is because those are the answers provided by my teacher's sample programs. I have already sent him my code and what you see up there is what my teacher said to do. Yet, I still have a differing output than the sample prog. Which is the reason I'm asking here on the forums. I was wondering if maybe the output is different because of system/compiler issues? I did some research online and they talked about Intel using "endian" values, and I'm on AMD. Maybe the sample program was …

ohnomis 36 Light Poster

Hello,

I've been having trouble trying to duplicate this program.

My output differs from the sample output I was given for homework. I don't understand whats wrong with my code.

void displayUnion( iUnion );

union integer_union
{
      char c;
      short s;
      int i;
      long l;
};

typedef union integer_union iUnion;

int main()
{
      iUnion value;

      /* char */
      printf( "Please enter a char: " );
      scanf( "%c", &value.c );
      displayUnion( value );

      /* short */
      printf( "%s", "Please enter a short: " );
      scanf( "%hd", &value.s );
      displayUnion( value );

      /* int */
      printf( "%s", "Please enter an int: " );
      scanf( "%d", &value.i );
      displayUnion( value );

      /* long */
      printf( "%s", "Please enter a long: " );
      scanf( "%ld", &value.l );
      displayUnion( value );
      
      /* ending code */
      system( "pause" );

      return 0;
} /* end main */

/* prints each variable in the union */
void displayUnion( iUnion passedIn )
{
      printf( "char  c = %c\n", passedIn.c );
      printf( "short s = %hd\n", passedIn.s );
      printf( "int   i = %d\n", passedIn.i );
      printf( "long  l = %ld\n\n", passedIn.l );
} /* end function displayUnion */

My result:

Please enter a char: a
char c = a
short s = -13215
int i = -858993567
long l = -858993567

Please enter a short: 1
char c = ☺
short s = 1
int i = -859045887
long l = -859045887

Please enter an int: …

ohnomis 36 Light Poster

If you are making a complex class you should return a complex object, and it should not be the first operand. I mean given z and w two complex number, the instruction z + w should not modify z! Instead, it should be used in an expression like c = z + w , assigning the result of the sum to another complex number c.

The member you need in this class are just Real and Imaginary, that are two double variables holding real and imaginary part of the compex number itself. You don't need to bother about calculating "i" (in fact, you couldn't even if you needed to). You should just append "i" as a char next to the imaginary value when you print the complex number on screen.

Here are examples:

Complex Complex::operator+(Complex op2) {
	Complex temp;
	temp.Real = Real + op2.Real;
	temp.Imaginary = Imaginary + op2.Imaginary;
	return temp;
}

to overload the operator+, and

std::ostream& operator<<(std::ostream& lhs, Complex& obj) {
	lhs << "(";
	if(obj.Real>=0) {
		lhs << "+" << obj.Real;
	}
	else {
		lhs << obj.Real;
	}
	if(obj.Imaginary>=0) {
		lhs << " +" << obj.Imaginary << "i";
	}
	else {
		lhs << " " << obj.Imaginary << "i";
	}
	lhs << ")";
	return lhs;
}

for output purposes.

Last but not least: square root of -1 is not -1.

And the winner is mrboolf. I managed to solve the problem with your tips. Your answer is much more accurate in regards to what I needed to do. Lemme add …

ohnomis 36 Light Poster

* -1
The square root of -1 is -1 we say. So it would just make your number negative.
Maybe this documentation is helpful for you too :)
http://en.wikipedia.org/wiki/Complex_number

I will take a look at wikipedia for a more mathematical answer. Its weird but my teacher's sample output has a different answer than mine even if it is negative lol. Guess theres something else wrong with my code then lol. Thank you for your help brechtjah.

ohnomis 36 Light Poster

Well,
the square root of 4 is 2 because 2*2 is 4. So the square root of x is a number which complies to this: y*y = x.
This works for every number that is positive, however, if you try to take the square root of -1, that means you want y

y*y = x
-1 * -1 = oops, no, it's not x!
it's 1 instead of -1. That means there is no square root of -1. We just say it is -1 because we want to be able to calculate complex numbers with it.

Maybe my previous explanation was a little short, I hope this helps :) feel free to ask questions

Sounds complicated lol, but I sorta get what you mean. =) So assuming a number * itself is = x
so if
2 * 2 = 4 // square root of 4 is equal to 2
-1 * -1 = doesn't work cuz all square roots are positive

so does this mean if i use

totalReal + totalImaginary * 1 // or don't even bother with the *1 since it does nothing

should give me the correct answer?

ohnomis 36 Light Poster

So you're saying it should be the same as:

int i = -1;

totalReal + totalImag + i;

Seems strange how the square root of -1 = -1...

ohnomis 36 Light Poster

Hello,

I'm writing a a program in C++ that adds/subtracts complex numbers. I'm having trouble writing the square root of -1 or "i" in a complex number.

Complex number:
realPart + imaginaryPart * i (where i is /-1) ["square root of -1"]

so far I'm thinking the code is something like this, but don't know how to go abouts to writing the square root part.

double Complex::plusEq( Complex secondComplex )
{
	double totalReal = real + secondComplex.getReal();
	double totalImag = imaginary + secondComplex.getReal();

	return totalReal + totalImag + // i; <--------- this part
}

I can't figure out how to write the commented "i".
Help please! ^^

ohnomis 36 Light Poster

Apparently, its not good to declare variables inside "case x" like the others have said. Everything worked when I declared it as a local variable outside the switch statement and used the variable "steps" inside the "case x" when needed.

Thanks to everyone's help, I managed to solve this problem. ++points for all of you. ^^

ohnomis 36 Light Poster

It compiles now that I put the steps inside the for loop, but not BEFORE the for loop:

for ( int cmd = 0; commands[ cmd ] != 9; cmd++ )
{
    int steps = command[ ++cmd ];
    
    switch ( commands[ cmd ]
    {
...
}

But won't this pre-increment cmd before it even enters the switch statement? I thought I want to increment cmd AFTER the switch statement determines that I want scenario 5, then use the incremented cmd to determine how many spots to move?

ohnomis 36 Light Poster

I'm actually still getting a compile error with that code.

error C2360: initialization of 'steps' is skipped by 'case' label
see declaration of 'steps'

I don't think I'm going with the right approach to this problem.

*I also tried putting steps in its own braces to give it local scope, ie.

{
     int steps = commands[ ++cmd ];
}

The error for this is now:

error C2065: 'steps' : undeclared identifier

Anyone else with a different approach to this problem maybe?

ohnomis 36 Light Poster

Hi everyone,

I have a question regarding reading commands from an array for a turtle graphics program.

5, x - Move forward x number of spaces (x being the next number in the array, ie. 5, 5)
4 - Turn right
9 - End commands (sentinel value)

If you have this array:

int commands[] = { 5, 5, 4, 5, 9, 9 }

These commands cause the turtle to move 5 spaces in whatever direction he's facing (the first 5 invokes the move command, while the next 5 in the array tells the turtle how many spaces to move). Then the next command is 4 which tells the turtle to turn right. Then the following 5, 9 tells the turtle to move 9 spaces forward.

Now, my problem is I have a for loop that reads these commands:

void TurtleGraphics::processTurtleMoves( const int commands[] )
{
	for ( int cmd = 0; commands[ cmd ] != 9; cmd++ )
	{
		switch ( commands[ cmd ] )
                {
			case 4: // turn right
				tDirection += 3;
				if ( tDirection > 12 )
				{
					tDirection -= 12;
				}
				break;
			case 5: //move forward x number of spaces
				int steps = commands[ cmd++ ];

				for ( int stepsTaken = 0; stepsTaken < steps; stepsTaken++ )
				{
					switch ( tDirection )
					{
						case 3: // turtle is facing right
							if ( penPos == 1 )
							{
								m_Floor[ tRow ][ tCol ] = 1;
							}
							tCol++
							break;
						case …
ohnomis 36 Light Poster

this may help

http://www.daniweb.com/forums/thread147970.html

I agree, look at my thread and hopefully the answer comes to you too. =)

ohnomis 36 Light Poster

>>but I dunno if its allowed here.
We won't have a problem with it. But think -- do you want other students and your teachers finding that code here on the net ? Don't post it unless you are sure you and your school are ok with that.

True, probably not a good idea anyways. =P

Oh yeah, thanks for your help too dragon. ++ Rep for you too even though it look like u don't need it lol. =P

Ancient Dragon commented: Good job working this out :) +36
ohnomis 36 Light Poster

OK WOW, its 5:34AM and it all just came to me. I actually have the right answer now. I'm edging to post the code, but I dunno if its allowed here. Either way, thanks for your help grumpier, theres no way I would've gotten the answer without you. ++Rep 4 you sir. =)

ohnomis 36 Light Poster

My code after another hour of thinking:

int iterations = 0;
	
	double answer = 1; // result of the current factorial calculation
	double result = 1;
	int n = 1;
	int pow_x = 1;

	while ( result > 1.0E-20) {
		pow_x = x * result;
		result = ( x / ( n + 1 ) ) * ( pow_x / ( n + 1 ) );
		cout << result << endl;
		n++;
		answer += result;
		iterations++;
	}
ohnomis 36 Light Poster

after reading your math, I feel my code is close to completion, but the only part that confuses me now is the factorial ( n ) part.

after seeing that formula you provided, I see that the result does calculate to a much smaller number.

Only bad part is that factorial ( n )'s answer is limited by how far i can take n!, which I am currently storing as a long long, so about 20 digits in is the max before i start getting garbage values.

This means my pow_x can't be divided by values higher than 20! which is my current mindboggler.

ohnomis 36 Light Poster

Well, I could. But that takes the challenge of problem solving away from you.

Look back in my previous posts in this thread for definition of T, n, etc.

VernonDozier has worked out what I'm saying which is evidence that, with a bit of effort, you will be able to as well.

True, you solving the problem wouldn't help me learn. =) I have one more day to solve this, due Tuesday, so I hope it comes to me by tomorrow. ^^ I feel I am so close, just missing a small piece of the pie lol. Can you at least tell me if I'm on the right track? =)

So far, this is what I've come up to:

double answer = 1; // result of the current factorial calculation
	double result = 1;
	double n = 0;
	int pow_x = 1;

	while ( result > 1.0E-20) {
		pow_x *= x;
		result = ( x / ( n + 1 ) ) * ( pow_x / factorial ( n ) );
		n++;
		answer += result;
		iterations++;
	}
ohnomis 36 Light Poster

Start with T(0) = 1.

In a loop use the fact that T(n+1) = x*T(n)/(n+1) to compute each term. Add the terms together.

Maybe you can simply explain what your T, n and x represent? From what I see, x is the value the user inputs and I have no idea where your n comes from. Like in your formula, the most I can see is:

cin << x;

n = ?
T = ?

Maybe you can use your formula in an actual code example?

ohnomis 36 Light Poster

Can you explain in detail how your math formula relates to my code? I think you understand the problem, but I can seem to relate that formula to my loop. Another issue is how can you store such a giant number to output to the terminal?

Take this simple example:

long long answer = 1;
double result = 0;
int currentFactor = 1;

while ( result > 1.0E-20) {
	pow_x *= x;
	result = pow_x / factorial ( currentFactor );
	currentFactor++;
	answer += result;
}

In my code, the loop will continue as long as the result of each calculation is greater than 0.00000000000000000001 (or something close to that which is a puny number).

pow_x *= x // this part calculates the x^1 part and goes up as more loops happen, for example when the second loop happens, it changes to x^2 and then x^3 and so forth.

pow_x then gets divided by factorial (currentFactor) which increments with each loop, ie. 1! for the first loop, then currentFactor increments so then 2! is next and 3!

then answer stores each calculation result and increases with each loop hence the answer+=result part of the loop.

In the end, it should keep looping until some crazy huge number is divided into another huge number, which should eventually reach a very small value less than 0.0000000000000000000001 and stop looping and stop. Which is what its doing now, however, the numbers after 20! appear to overflow due to …

ohnomis 36 Light Poster

If its so trivel post the code. Your code needs to come up with
562262574607502830000000000000000000000000000000
00000000000000000000.0000000000


That number is too huge for normal c-language math.

Thanks Dragon for helping me for the last couple hours. I added the teacher's question to see if it helps you any. Strange question tho, the teacher basically said create a program that calculates e^x. And thats basically it! Well that and use a while loop to do it. Then he gives us that sample program, which posted 2 scenarios one with an input value of 1 and the other with the input value of 156 which gives u that huge number u posted above.

I wish I had more information for you, but thats basically it lol. I think i should change teacher's next semester lol.

ohnomis 36 Light Poster

Oh, please! Huge integer libraries or strings are needed for some things, but falling back on them for basic problems like this is crazy.

The program can go to much higher terms simply using the fact that e^x = 1 + x/1! + x^2/2! + ... and that the n-th term inthis is T(n) = x^n/n! It is trivial to show that T(n+1) = x*T(n)/(n+1).

The code to use this relationship to compute an approximation of e^x is easy. This avoids the possibility of overflow that is inherent in computing x^n or n! separately.

Thanks for the reply grumpier, and it seems like you know what you are talking about in regards to this issue.

Included here is the teacher's clue:

You can compute the approximation for e^x without using a power function (you can actually calculate a more accurate solution without using a power function). Again, you should study the difference between term n and term n+1 and deduce the most efficient algorithm for computing term n+1 when you have already calculated term n.

So basically, I think the teacher wants us to calculate e^x (which is = to

1 + x^1 / 1! + x^2 / 2! + x^3 / 3! + ...

I'm guessing this has something to do with the difference between n and term n+1? this is the part that I don't get.

and that the n-th term inthis is T(n) = x^n/n! It is trivial to show that …

ohnomis 36 Light Poster

Well the program is an .exe that he provided and wanted us to mimic the functionality of it. Its basically no different from what I posted above, and I can't view the source code. I can post another example I suppose.

Input a value for x between 1 and 156: 1

e raised to the 1.00 power is 2.7182818285

The number of terms computed is 23

Press any key to continue . . .

I will post the EXACT question below this post.

ohnomis 36 Light Poster

Actually, now I see the the problem with the overflow and my calculation.

I'm trying to divide x / 1! + x^2 / 2! + ...
and so forth, so eventually I think the program reaches x^21 / 21! and my variable "long long" can't store 21! since "long long" can only store up to 20 digits I believe. However, a sample program my teacher and given us can calculate up to 156 as the X value...meaning his calculations should be going from:

156^1 / 1! + onwards... until a number that is smaller than 10E-20 is reached. Below is a sample output from his .exe program.

Input a value for x between 1 and 156: 156

e raised to the 156.00 power is 562262574607502830000000000000000000000000000000
00000000000000000000.0000000000

The number of terms computed is 466

Press any key to continue . . .

I believe mine is going nuts after 20!, but i have no idea how his could go up to 156? Am I missing something here?

ohnomis 36 Light Poster

I see what you mean now. By printing the results of the factorial loop, once the number gets too big, it starts changing into funny numbers. (The overflow you were talking about).

How do I go about solving this overflow problem? Should I limit the results of my factorial function to a certain number of digits? If so, how do I go about doing that? Do I store the value in a variable declared as an int instead of a long long maybe?

ohnomis 36 Light Poster

Thanks, I tried that, but it didn't do anything to explain the negative number at the end of the results.

ohnomis 36 Light Poster

Hi, I've just started a course in C++ about 3 weeks ago. Unfortunately, I'm pretty lost at the moment with this problem and my teacher said I'm on my own now. (I'm guessing he doesn't want to answer my questions anymore because I ask too many, but I really don't understand).

Anyways, as my last resort I've decided to join this forum and ask here because I've got lots of help from old threads from this forum.

The situation is a factorial problem:

I need to create a program that calculates e^x = 1 + x/1! + x^2/2! + ... and so forth.

I input the value for x, and the program should keep calculating until it reaches a number less than 1.0E-20 and terminates because the value is too small to make a different to the answer. Then the program returns how many terms it used to get to the result. (I'm guessing th it means the "accuracy" or iterations it took to come to this conclusion. I need to do this using a while loop.

So far my code looks llike this:

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ios;

#include <iomanip>
using std::setw;
using std::setprecision;
using std::setiosflags;

// factorial calculation (e = 1/1! + 1/2! + ...)
long long factorial( int num )
{
	long long answer = 1;
	while ( num > 1 ) {
		answer *= num;
		num--;
	}

	return answer;
}

// start of function main …