EverCrest Message Forums
You are not logged in. Login or Register.
Author
Topic: Interesting C++ error
Beta is in school
Pancake
posted 10-21-2002 01:34:02 PM
code:
 #include <iostream>
using namespace std;

int main()
{
double postotal;
double negtotal;
int posnumber;
int negnumber;
double add;
add = 1;
posnumber = 0;
negnumber = 0;
postotal = 0;
negtotal = 0;
while (add != 0)
{
cout << "Enter a number: ";
cin >> add;
if (add > 0)
{
postotal += add;
posnumber++;
}
else if (add < 0)
{
negtotal += add;
negnumber++;
}

}

cout << postotal / posnumber << " is the average of positive numbers" << endl;
cout << negtotal / negnumber << " is the average of negative numbers" << endl;
}


When I input 0 it will return
-1.#IND for the average of both numbers. Any ideas why?

I'm not asking you to fix the code, because it already works, and is much smaller than anything my peers managed to pull out of their asses.

Blindy
Roll for initiative, Monkey Boy!
posted 10-21-2002 02:15:59 PM
ok couple of problems i can see.

first off, if i start out by entering 0, I will get a div/0 error that kills the code.

Same holds true if i only enter one number, beit positive or negative, i will get a div/0 error.

you don't NEED the second if statment, if it's not 0 and it's not positive, then it's negative. some professors might applaud that, but when you are programming larger programs, saving every code branch you can will not only make the code easier on your eyes, but can make it execute faster.

you can declare a variable and define it at the same time, cuts off a few lines of code

if they put in a non numeric value or something beyond the int range of 32,657, it will crash your program some error checking would be a good idea here

i would suggest having it cout what the user entered every loop so you can make sure it is reading the code right

On a plane ride, the more it shakes,
The more I have to let go.
Beta Tested
Pancake
posted 10-21-2002 09:23:04 PM
To refresh, I'm not getting any fatal errors in the code, everything works fine.

I'm getting NO errors when I divide by zero, just that crazy thing that claims it's an integer.

I want to know if any of you knows why, because me and my teacher are both stumped to hell and back. Even my friend Brian who's right up there with me when it comes to speed and efficentcy in the class can't figure it out.

Blindy, I suppose that would be a good way to cut the code even more, but remember, in C++ the loop var doesn't get checked til the bottom of the loop.

[edit] BTW, that crazy nubmer up there, I get that if I enter 0 as the first thing, or only one pos number, the neg comes out that.

[ 10-21-2002: Message edited by: Beta Tested ]

What's this thing do?
That would be sooo cool if it wasn't going to hurt us.
Melphina's Magelo
All times are US/Eastern
Hop To: