Author Topic: I wrote my first bit of source code!  (Read 20175 times)

0 Members and 1 Guest are viewing this topic.

Offline Freespace Freak

  • 28
  • Official forum permanewb
Re: I wrote my first bit of source code!
Ok theres something funky going on here....

NGrades is set to 0
and Average = Sum / NGrades works correctly  :confused:

It should throw a divide by zero error.
Quote
Division by 0 in either a division or a modulus expression is undefined and causes a run-time error. Therefore, the following expressions generate undefined, erroneous results:
i % 0
f / 0.0

Hmmm, your right, but it doesn't cause an error when I run the program.  Perhaps it just sees the error, ignores it, then moves on.  However, it won't see the error when it compiles the program, because NGrades is unknown until DataIn is entered.  Anyway, it works as is, the question I guess is why, but I fixed it regardless.  Here it is.

Code: [Select]
#include<iostream>
using namespace std;
#include<cmath>
int main(void)
{

//declare variables
double DataIn, Average, Sum;
int    NGrades, Value;

//print title
cout << "Program \x22";
cout << "Average\x22 \n\n";
cout << "This program calculates the average of an arbitrary number\n";
cout << "of grades.\n\n";
cout << "After all the grades have been entered, any negative number\n";
cout << "is entered, and the averaging is performed.\n\n";
//get input
NGrades = 0;
Sum = 0.0;
Value = 0;

while (Value == 0)
{
cin >> DataIn;
if (DataIn >= 0)
{
Value = 0;
Sum = DataIn + Sum;
++NGrades;
}
else (++Value);
}

//calculate
if (NGrades >0)
Average = Sum / NGrades;

//output data
switch (NGrades)
{
case 0:
cout << "\nNo valid grades have been entered.\n\n";
cout << "An average cannot be computed.";
break;
case 1:
cout << "\nThere is only one grade whose value is " << Average << ".";
break;
default:
cout << "\nThere are " << NGrades << " grades, with an average of " << Average << ".";

}

cout << "\n\n";
return 0;
}

 
Re: I wrote my first bit of source code!
That'll fix the problem  ;)

Actually NGrades is known... you set it to zero right after //get input
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"

  

Offline Freespace Freak

  • 28
  • Official forum permanewb
Re: I wrote my first bit of source code!
That'll fix the problem  ;)

Actually NGrades is known... you set it to zero right after //get input

Yeah, but why did I not get a runtime error before?  I would run the program, enter -1 as my first grade, and it would execute case 0.  I would not get a runtime error.  Why is that?  I use VC++6 and 8, and it runs fine without the runtime error on both of them.  Do you get one with yours?  What kind of compiler do you use?

 
Re: I wrote my first bit of source code!
.NET 2003

Ahhh take a look at the value of Average after doing the division.... it's NaN  (Not a Number)
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"

 

Offline taylor

  • Super SCP/Linux Guru
  • Moderator
  • 212
    • http://www.icculus.org/~taylor
Re: I wrote my first bit of source code!
Yeah, but why did I not get a runtime error before?  I would run the program, enter -1 as my first grade, and it would execute case 0.  I would not get a runtime error.  Why is that?
The rules for this are slightly different because it's float-point based math, not integer based.

Floating-point math should give you a predictable result (ie, NaN or INF), but probably not generate an error (this can be compiler/CPU dependent though).  The result can later generate a runtime error if you act upon that result however (ie, if "Average" is NaN, then it could segfault if you then do "Sum /= Average").  So it's still a good idea to check for and/or prevent div-by-0 errors, since otherwise you'll probably need to check for NaN at some point to prevent crashes that may be a little more difficult to track down.

In integer math you should get an instant runtime error (some CPUs can actually handle the error, giving 0 as the result).


It may only take a matter of seconds to fix a div-by-0 related crash since it happens relatively instantly.  With something like NaN errors though, I've spent (on several occasions) the better part of a day tracing through the FSO code looking for the cause of a NaN related crash.  Because NaN related problems can happen much later in the program they are really something that you want to avoid.

 

Offline Freespace Freak

  • 28
  • Official forum permanewb
Re: I wrote my first bit of source code!
Hmm, NGrades is an integer, but since Sum is a double and is the sum of all DataIn, which is also double, then it performs float point math, as apposed to integer math.  Makes sense, makes sense.

 

Offline Freespace Freak

  • 28
  • Official forum permanewb
Re: I wrote my first bit of source code!
Er, I'm having problems.   :nervous:  I e-mailed my professor, but he hasn't responded to me.  I thought perhaps I can use the expertise here at the HLP to help me. ;)  So, for this assignment, we got to make this program based off of our mid-term exam.  No biggie, it's kinda like the last one where the average of a bunch of numbers is performed.  This time, however, the user inputs letter grades, but only the following letter grades: A, C, and F.  A is equivalent to 95, C is 75, and F is 50.  Once the user inputs any letter that is not an a, c, or an f, the average of all the grades entered is performed.  You can do this all with one nice main function, which we did for the mid-term, but for this assignment our professor wants us to make the title and the part where it converts a letter to it's numerical equivalent part of separate functions outside the main, since we're doing user defined functions now.  The title function is a piece of cake, but the other one is killing me.  I can't get it to work the way I want it to.  What I want it to do, is take a character, that I called DataIn, and convert it to a double number, which I call Value.  No matter what I do, I can't make a function do that.  Here's what I got so far (that doesn't work).

Code: [Select]
//Mid-Term Exam Revisited
#include<iostream.h>
void Title (void);
double Convert (char DataIn);

int main (void)
{
double Sum = 0.0, Average, Value;
char   DataIn;
int    NGrades = 0, close = 0;

Title (); //Print Title

//Prompt and get Data
while (close == 0)
{


cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
if (DataIn >= 97)
DataIn = DataIn - 32;
Convert (DataIn);
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}
else ++close;

}


//Calculate
if (NGrades > 0)
Average = Sum / NGrades;

//Output Results
switch (NGrades)
{
case 0:
cout << "\nNo valid grades have been entered.";
break;
case 1:
cout << "\nOnly one grade has been entered whose value is "<< Sum;
break;
default:
cout << "\nThe average of " << NGrades << " grades is " << Average;
}

cout << "\n\n";
return 0;
}

void Title (void)
{
cout << "This program computes averages using three letter grades.\n\n";
  cout << "A = 95, C = 75, F = 50. Any other letter stops data entry.\n\n";
}
double Value (char DataIn)
{
double Value = 0.0;
switch (DataIn)
{
    case 'A':
      Value = 95.0;
break;
    case 'C':
      Value = 75.0;
break;
    case 'F':
      Value = 50.0;
break;
    default:
      Value = -1;
}
 
return (Value);
  }

Now, I know that the switch statement in the Value function works, and that the while statement in the main function works.  This I confirmed by getting rid of the Value function and placing it's switch statement directly in the spot where it's supposed to be within the while statement of the main function.  When I do that the program works.  It looks like this:

Code: [Select]
//Mid-Term Exam Revisited
#include<iostream.h>
void Title (void);

int main (void)
{
double Sum = 0.0, Average, Value;
char   DataIn;
int    NGrades = 0, close = 0;

Title (); //Print Title

//Prompt and get Data
while (close == 0)
{


cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
if (DataIn >= 97)
DataIn = DataIn - 32;
switch (DataIn)
{
    case 'A':
      Value = 95.0;
break;
    case 'C':
      Value = 75.0;
break;
    case 'F':
      Value = 50.0;
break;
    default:
      Value = -1;
}
 
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}
else ++close;

}


//Calculate
if (NGrades > 0)
Average = Sum / NGrades;

//Output Results
switch (NGrades)
{
case 0:
cout << "\nNo valid grades have been entered.";
break;
case 1:
cout << "\nOnly one grade has been entered whose value is "<< Sum;
break;
default:
cout << "\nThe average of " << NGrades << " grades is " << Average;
}

cout << "\n\n";
return 0;
}

void Title (void)
{
cout << "This program computes averages using three letter grades.\n\n";
  cout << "A = 95, C = 75, F = 50. Any other letter stops data entry.\n\n";
}

Can anybody point to me where I'm going wrong?   :confused:

 

Offline AdmiralRalwood

  • 211
  • The Cthulhu programmer himself!
    • Skype
    • Steam
    • Twitter
Re: I wrote my first bit of source code!
Granted I'm no expert, but I notice you have
Code: [Select]
double Value = 0.0;in the first version but not in the second. Since "double Value" is the exact same name as your function, perhaps that's the cause of your problem?
Ph'nglui mglw'nafh Codethulhu GitHub wgah'nagl fhtagn.

schrödinbug (noun) - a bug that manifests itself in running software after a programmer notices that the code should never have worked in the first place.

When you gaze long into BMPMAN, BMPMAN also gazes into you.

"I am one of the best FREDders on Earth" -General Battuta

<Aesaar> literary criticism is vladimir putin

<MageKing17> "There's probably a reason the code is the way it is" is a very dangerous line of thought. :P
<MageKing17> Because the "reason" often turns out to be "nobody noticed it was wrong".
(the very next day)
<MageKing17> this ****ing code did it to me again
<MageKing17> "That doesn't really make sense to me, but I'll assume it was being done for a reason."
<MageKing17> **** ME
<MageKing17> THE REASON IS PEOPLE ARE STUPID
<MageKing17> ESPECIALLY ME

<MageKing17> God damn, I do not understand how this is breaking.
<MageKing17> Everything points to "this should work fine", and yet it's clearly not working.
<MjnMixael> 2 hours later... "God damn, how did this ever work at all?!"
(...)
<MageKing17> so
<MageKing17> more than two hours
<MageKing17> but once again we have reached the inevitable conclusion
<MageKing17> How did this code ever work in the first place!?

<@The_E> Welcome to OpenGL, where standards compliance is optional, and error reporting inconsistent

<MageKing17> It was all working perfectly until I actually tried it on an actual mission.

<IronWorks> I am useful for FSO stuff again. This is a red-letter day!
* z64555 erases "Thursday" and rewrites it in red ink

<MageKing17> TIL the entire homing code is held up by shoestrings and duct tape, basically.

 
Re: I wrote my first bit of source code!
Oh I think I see the problem without even compiling it  :)

Code: [Select]
Convert (DataIn);
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}

Your forgetting to assign Value the result from Convert
Code: [Select]
Value = Convert (DataIn);
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"

 
Re: I wrote my first bit of source code!
BTW replace int close = 0 with bool close = false

replace while (close == 0) with while (!close)

and finally

replace else close++ with else close = true

close is an on/off toggle flag.. better to use bool for those.
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"

 

Offline AdmiralRalwood

  • 211
  • The Cthulhu programmer himself!
    • Skype
    • Steam
    • Twitter
Re: I wrote my first bit of source code!
...I can't belive I didn't notice that. Should've just kept lurking, I guess. :P
Ph'nglui mglw'nafh Codethulhu GitHub wgah'nagl fhtagn.

schrödinbug (noun) - a bug that manifests itself in running software after a programmer notices that the code should never have worked in the first place.

When you gaze long into BMPMAN, BMPMAN also gazes into you.

"I am one of the best FREDders on Earth" -General Battuta

<Aesaar> literary criticism is vladimir putin

<MageKing17> "There's probably a reason the code is the way it is" is a very dangerous line of thought. :P
<MageKing17> Because the "reason" often turns out to be "nobody noticed it was wrong".
(the very next day)
<MageKing17> this ****ing code did it to me again
<MageKing17> "That doesn't really make sense to me, but I'll assume it was being done for a reason."
<MageKing17> **** ME
<MageKing17> THE REASON IS PEOPLE ARE STUPID
<MageKing17> ESPECIALLY ME

<MageKing17> God damn, I do not understand how this is breaking.
<MageKing17> Everything points to "this should work fine", and yet it's clearly not working.
<MjnMixael> 2 hours later... "God damn, how did this ever work at all?!"
(...)
<MageKing17> so
<MageKing17> more than two hours
<MageKing17> but once again we have reached the inevitable conclusion
<MageKing17> How did this code ever work in the first place!?

<@The_E> Welcome to OpenGL, where standards compliance is optional, and error reporting inconsistent

<MageKing17> It was all working perfectly until I actually tried it on an actual mission.

<IronWorks> I am useful for FSO stuff again. This is a red-letter day!
* z64555 erases "Thursday" and rewrites it in red ink

<MageKing17> TIL the entire homing code is held up by shoestrings and duct tape, basically.

 
Re: I wrote my first bit of source code!
Granted I'm no expert, but I notice you have
Code: [Select]
double Value = 0.0;in the first version but not in the second. Since "double Value" is the exact same name as your function, perhaps that's the cause of your problem?

Those two double Value 's are totally different variables, they occur on different scopes.
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"

 

Offline StratComm

  • The POFressor
  • 212
  • Cameron Crazy
    • http://www.geocities.com/cek_83/index.html
Re: I wrote my first bit of source code!
Any good compiler will see the difference between "Value" and "Value(...)" though I'm a little surprised you didn't see a warning.  Scope actually has nothing to do with it in this case, as there's a very real risk of infinite recursion if you aren't careful with the way that's written.

And I think convention is generally to not use drop caps for variables and only use it for functions, but that's just convention. 

BTW replace int close = 0 with bool close = false

replace while (close == 0) with while (!close)

and finally

replace else close++ with else close = true

close is an on/off toggle flag.. better to use bool for those.

Bools are so overrated.  They don't save any memory and their underlying representation is usually an int anyway.  They're good for reducing confusion but functionally is exactly the same.
who needs a signature? ;)
It's not much of an excuse for a website, but my stuff can be found here

"Holding the last thread on a page comes with an inherent danger, especially when you are edit-happy with your posts.  For you can easily continue editing in points without ever noticing that someone else could have refuted them." ~Me, on my posting behavior

Last edited by StratComm on 08-23-2027 at 08:34 PM

 
Re: I wrote my first bit of source code!
Wait a moment.....
shouldn't the function Value be named Convert instead?
Code: [Select]
double Value (char DataIn)
{
double Value = 0.0;
switch (DataIn)
{
    case 'A':
      Value = 95.0;
break;
    case 'C':
      Value = 75.0;
break;
    case 'F':
      Value = 50.0;
break;
    default:
      Value = -1;
}
 
return (Value);
  }

Compared with the predefintion and how you used it in the main function
Code: [Select]
double Convert (char DataIn);
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"

 
Re: I wrote my first bit of source code!
Bools are so overrated.  They don't save any memory and their underlying representation is usually an int anyway.  They're good for reducing confusion but functionally is exactly the same.

For size differences I agree, no difference.  But for clarity they can do a lot.  Compared to close++ and close = true.
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"

 

Offline AdmiralRalwood

  • 211
  • The Cthulhu programmer himself!
    • Skype
    • Steam
    • Twitter
Re: I wrote my first bit of source code!
...I can't believe I didn't notice that one, either. Definately should've just kept lurking.
Ph'nglui mglw'nafh Codethulhu GitHub wgah'nagl fhtagn.

schrödinbug (noun) - a bug that manifests itself in running software after a programmer notices that the code should never have worked in the first place.

When you gaze long into BMPMAN, BMPMAN also gazes into you.

"I am one of the best FREDders on Earth" -General Battuta

<Aesaar> literary criticism is vladimir putin

<MageKing17> "There's probably a reason the code is the way it is" is a very dangerous line of thought. :P
<MageKing17> Because the "reason" often turns out to be "nobody noticed it was wrong".
(the very next day)
<MageKing17> this ****ing code did it to me again
<MageKing17> "That doesn't really make sense to me, but I'll assume it was being done for a reason."
<MageKing17> **** ME
<MageKing17> THE REASON IS PEOPLE ARE STUPID
<MageKing17> ESPECIALLY ME

<MageKing17> God damn, I do not understand how this is breaking.
<MageKing17> Everything points to "this should work fine", and yet it's clearly not working.
<MjnMixael> 2 hours later... "God damn, how did this ever work at all?!"
(...)
<MageKing17> so
<MageKing17> more than two hours
<MageKing17> but once again we have reached the inevitable conclusion
<MageKing17> How did this code ever work in the first place!?

<@The_E> Welcome to OpenGL, where standards compliance is optional, and error reporting inconsistent

<MageKing17> It was all working perfectly until I actually tried it on an actual mission.

<IronWorks> I am useful for FSO stuff again. This is a red-letter day!
* z64555 erases "Thursday" and rewrites it in red ink

<MageKing17> TIL the entire homing code is held up by shoestrings and duct tape, basically.

 
Re: I wrote my first bit of source code!
Thats where I was going with the scope issues.  At the time I didn't even see Value () [my mind must have thought Convert ()]
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"

 

Offline Freespace Freak

  • 28
  • Official forum permanewb
Re: I wrote my first bit of source code!
Wait a moment.....
shouldn't the function Value be named Convert instead?

Wait a moment.....
shouldn't the function Value be named Convert instead?

Yes.   :nervous:  I was going in between naming it Value and Convert, so you would see Value (DataIn) in that spot instead of Convert (DataIn).  When I posted, I was going from naming the function Value to Convert, and I didn't realize that the function name itself hadn't been changed.  My bad.  But yes, you fixed it Scoob.  :yes:  You get Scooby snacks!   :P  Just putting in the Value = Convert (DataIn) fixed it.  The whole bool stuff works, and I understand boolean algebra, but I can't remember if we actually covered that in class.  However, the other method works just as well.  I'll use my method, until I know it's okay for me to use bool.  Here's my finalized and working code:
Code: [Select]
//Mid-Term Exam Revisited
#include<iostream.h>
void Title (void);
double Convert (char DataIn);

int main (void)
{
double Sum = 0.0, Average, Value;
char   DataIn;
int    NGrades = 0, close = 0;

Title (); //Print Title

//Prompt and get Data
while (close == 0)
{
cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
Value = Convert (DataIn);
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}
else ++close;
}


//Calculate
if (NGrades > 0)
Average = Sum / NGrades;

//Output Results
switch (NGrades)
{
case 0:
cout << "\nNo valid grades have been entered.";
break;
case 1:
cout << "\nOnly one grade has been entered whose value is "<< Sum;
break;
default:
cout << "\nThe average of " << NGrades << " grades is " << Average;
}

cout << "\n\n";
return 0;
}

void Title (void)
{
cout << "This program computes averages using three letter grades.\n\n";
  cout << "A = 95, C = 75, F = 50. Any other letter stops data entry.\n\n";
}
double Convert (char DataIn)
{
double Value;
if (DataIn >= 97)
DataIn = DataIn - 32;
switch (DataIn)
{
    case 'A':
      Value = 95.0;
break;
    case 'C':
      Value = 75.0;
break;
    case 'F':
      Value = 50.0;
break;
    default:
      Value = -1;
}
 
return (Value);
  }

This same program was on the Mid-term, except we did it all in the main function.  What my professor did for the while loop required the input prompt to be placed in the code twice, once before the while loop, and one inside the while loop.  Like this:
Code: [Select]
        cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
Value = Convert (DataIn);

        while (Value > 1)
{
                Sum = Sum + Value;
++NGrades;

cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
Value = Convert (DataIn);
}
That works, but, not to criticize my own professor, it looks sloppy.  I think putting everything within the loop without having to put any statements in front of it to make it work is a better way of doing things.
« Last Edit: November 03, 2006, 08:07:12 am by Freespace Freak »

 
Re: I wrote my first bit of source code!
I guess the best suggestions for loops is put only what absolutely has to go in a loop and leave everything else out.  A slightly less chance of additional errors and more optimized  :)
That's cool and ....disturbing at the same time o_o  - Vasudan Admiral

"Don't play games with me. You just killed someone I like, that is not a safe place to stand. I'm the Doctor. And you're in the biggest library in the universe. Look me up."

"Quick everyone out of the universe now!"