Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0

    How does a stupidly simple program like this crash?


    Ok ok...I've read the sticky "rules" thread at the top of the forum, and I know that putting up a topic title like this is a big no-no, but I've got no idea as to how else I should word it.

    I'm a newbie in programming (so go easy on me please) and I started with C. Whatever I try doing, I try it using some experimentation and my common sense (the book I was using was going WAAAY too slow). I tried coding this kindergarten-ish app that allows the user to choose to calculate either the side or the angle of a triangle using the cosine rule. Here's the code (yes I also know that putting up the entire code is also a big no-no, but the entire app is only a few line):

    Code:
    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h>
    
    main()
    
    {
          char opt;
          float a, b, c, x;
          
          puts("Please note that 'a', 'b' & 'c' represent the three sides of a triangle,");
          puts("while 'x' is the angle between 'b' and 'c'.\n");
          
          printf("Do you want to calculate the lenght [a] or angle [x]?\n");
          
          scanf("%c", opt);
          
          if (opt=a)
          {
                    printf("\nPlease enter the values for");
                    printf("\nb: ");
                    scanf("%f", &b);
                    printf("c: ");
                    scanf("%f", &c);
                    printf("and x: ");
                    scanf("%f", &x);
                
                    a=sqrt(pow(b, 2)+pow(c, 2)-(2*b*c*cos(x)));
          
                    printf("\nThe value of \"a\" is %f.", a);
          
                    getchar();
          
                    return 0;
          }
          
          else if (opt=x)
          {
                    printf("\nPlease enter the values for");
                    printf("\na: ");
                    scanf("%f", &a);
                    printf("b: ");
                    scanf("%f", &b);
                    printf("and c: ");
                    scanf("%f", &c);
                    
                    x=acos((pow(b, 2)+pow(c, 2)-pow(a,2))/(2*b*c));
                    
                    printf("\nThe value of \"x\" is %f.", x);
                    
                    getchar();
                    
                    return 0;
          }
          
          else
          {
                    printf("\nInvalid command!\n");
                    
                    getchar();
                    
                    return 0;
          }
    }
    Now what happens is it goes up to the point where it asks the user to choose between calculating the angle or the lenght of a side. But regardless of whatever key I press, the program simply crashes. The debugger didn't show any errors, so I'm a bit clueless. But when I started coding it, I wrote the app to only calculate the lenght of the side (so no "if" statements back then); and it worked. So what could be wrong here?

    Also, I've got a few other questions:

    1) When I was initially testing the unfinished program, I found that the values of any angles are automatically considered in radian. How would I code so that the angles are in degrees? Better yet, how would I code it so the user gets to choose between degrees and radian?

    2) How do I get the answers to round up to a certain number (say three) decimal places?

    3) How on earth can I get the program to display Unicode characters (e.g. the "theta" sign, etc.)?
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,325
    Rep Power
    2228
    In this line, scanf("%c", opt);, you need to pass the address of opt to scanf(), not the value of opt. I assume that scanf() interpreted that value (which is garbage, the standard contents of an uninitialized variable) as an address, which in most such cases must have pointed to an address for which your program does not have access. You can expect the same results if you ever try to use an uninitialized pointer.

    Look at your scanf()'s in the if-statement's code block, where you did it correctly.

    1) When you get to series in 3rd semester calculus, you will find that the Taylor/Maclaurin series for calculating trig functions depend on angles being in radians. Since that is how the math library does it, the trig functions require radians. Simple solution is to have the user input degrees which you convert to radians.
  4. #3
  5. Lord of Dorkness
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2004
    Location
    Central New York. Texan via Arizona, out of his element!
    Posts
    8,524
    Rep Power
    3319
    See "Commonly Asked Questions", post #2 (scanf failures). I can break your program with two keystrokes.
    Functionality rules and clarity matters; if you can work a little elegance in there, you're stylin'.
    If you can't spell "u", "ur", and "ne1", why would I hire you? 300 baud modem? Forget I mentioned it.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0
    Originally Posted by dwise1_aol
    In this line, scanf("%c", opt);, you need to pass the address of opt to scanf(), not the value of opt. I assume that scanf() interpreted that value (which is garbage, the standard contents of an uninitialized variable) as an address, which in most such cases must have pointed to an address for which your program does not have access. You can expect the same results if you ever try to use an uninitialized pointer.

    Look at your scanf()'s in the if-statement's code block, where you did it correctly.

    1) When you get to series in 3rd semester calculus, you will find that the Taylor/Maclaurin series for calculating trig functions depend on angles being in radians. Since that is how the math library does it, the trig functions require radians. Simple solution is to have the user input degrees which you convert to radians.
    Okay...so I've understood you correctly, then I made the silly mistake of not putting the "&" before opt in scanf. (i.e. scanf("%c", &opt). I've corrected that (thanks for pointing that out!). But now there's another problem: no matter what character I input (even a or x), the program goes straight to the "else" block.

    About the radian/degree bit: yes I've thought of that and it seems like viable option, however I'd prefer it if the program were flexible enough to let the user choose between how the input/output value of the angle is to be considered. And either way, I still don't know the code for doing the conversion itself.

    And thanks for the reply. :)
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Mar 2004
    Posts
    855
    Rep Power
    1396
    Assignment
    Code:
    if (opt=a)
    versus comparison :D
    Code:
    if (opt == 'a')
    BTW converting degrees to radians and vice versa is easy.
    Code:
    #define PI 3.14159265
    
    double degreeToRadian(double degree){
    	double radian = 0;
    	radian = degree * (PI / 180);
    	return radian;
    }
    Last edited by holodoc; September 2nd, 2010 at 04:14 PM.
    PHP Code:
    <?php
    abstract class Ignorance extends Stupidity implements Unavoidable 
         public static 
    $humiliation

         private function 
    __construct(){
            
    parent::__destruct();
         }; 

    ?>
  10. #6
  11. Hats off to Mr. Joseph donahue
    Devshed Novice (500 - 999 posts)

    Join Date
    Aug 2009
    Posts
    752
    Rep Power
    1111
    3. I am not sure, but result may vary from computer to computer.
    Code:
     #include<stdio.h>
    
    int main()
    {
    	for(int i=0;i<255;i++)
    	{
    		printf("%c",i);
    	}
       return 0;
    }
    what did you get? A few strange characters are just the non printable characters like CR and LF. Apart from that all the symbols should be there for any decent compiler.

    2. That is an easy one, If you want a rough 3 digit float value, You can use printf as well to achieve this. otherwise learn to use google or RTFM (read the manual). Search for a similar function.
    The syntax:
    Code:
    printf("%.3f",12345.12345);
    1. answered by dwise1_aol better than I could.

    0. you return 0 in main, but your main looks like a headless monster, why? Its int main().
    Also, check the return values of scanf.
    Last edited by RAJ_55555; September 2nd, 2010 at 04:18 PM.
  12. #7
  13. Lord of the Dance
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Oct 2003
    Posts
    4,203
    Rep Power
    2012
    You also want to compare with char 'a' instead of the variable a. The same goes for char 'x'.
  14. #8
  15. Wiser? Not exactly.
    Devshed God 2nd Plane (6000 - 6499 posts)

    Join Date
    May 2001
    Location
    Bonita Springs, FL
    Posts
    6,276
    Rep Power
    4193
    Originally Posted by TheAbsentFriend
    About the radian/degree bit: yes I've thought of that and it seems like viable option, however I'd prefer it if the program were flexible enough to let the user choose between how the input/output value of the angle is to be considered. And either way, I still don't know the code for doing the conversion itself.
    The library functions only accept radian's. If you want to give the users the option of entering either, then that's a feature you need to build yourself.

    Create a way for them to specify their preference and save that information in a variable somewhere. Then for every input operation, check what their preference is. If they choose to use degrees then convert their input to radians before using it. If they choose to use radians then just use their input directly and skip the conversion process.
    If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud
  16. #9
  17. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,119
    Rep Power
    1807
    You are asking people here to debug your code. You would do better to learn debugging techniques.

    For starters you should:
    • Set the compiler warning level high; e.g. -Wall in GCC or \W4 in VC++
    • Regard warnings as errors -Werror in GCC, \Wx in VC++
    • Understand and fix all warnings before asking for help on a forum. Ask about how to fix the warning if you are unsure what it is telling you.


    I compiled your code unchanged in VC++ and it yielded:

    Code:
    
    sandbox.c(7) : warning C4431: missing type specifier - int assumed. Note: C no longer supports default-int
    sandbox.c(18) : warning C4244: '=' : conversion from 'float' to 'char', possible loss of data
    sandbox.c(28) : warning C4244: '=' : conversion from 'double' to 'float', possible loss of data
    sandbox.c(37) : warning C4244: '=' : conversion from 'float' to 'char', possible loss of data
    sandbox.c(47) : warning C4244: '=' : conversion from 'double' to 'float', possible loss of data
    sandbox.c(18) : warning C4706: assignment within conditional expression
    sandbox.c(37) : warning C4706: assignment within conditional expression
    sandbox.c(16) : warning C4700: uninitialized local variable 'opt' used
    sandbox.c(18) : warning C4700: uninitialized local variable 'a' used
    sandbox.c(37) : warning C4700: uninitialized local variable 'x' used
    Correctly resolving these would fix many of the errors in your code. It has not trapped the scanf() error but GCC will with the -Wformat warning option (which in GCC 4.x is implied by -Wall I think).

    Next learn to use a debugger. This will at least indicate exactly where your code crashes (as well as enabling detailed white-box testing and debugging of non-crashing functionality). In most cases, by stepping the code and inspection of the variable state, you can find the error before the code crashes. VC++ has an excellent and easy to use debugger, GDB (used with GCC) is somewhat less friendly, being entirely command line driven, although there are number of GUI wrappers and IDE integrations that make it easier to use (except if you are using Dev-C++ that is :rolleyes: whose GDB integration sucks bigtime! )
    Last edited by clifford; September 2nd, 2010 at 05:41 PM.
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2009
    Posts
    194
    Rep Power
    76
    Revisiting that way too slow C book, appears to be needed. You're missing some basic C essentials here.

    Be patient, and try studying it again. Give yourself some time, and I'm sure you'll be rewarded.
    Last edited by Adak; September 4th, 2010 at 03:21 PM.
  20. #11
  21. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Alpharetta, GA
    Posts
    1,809
    Rep Power
    1574
    If you don't mind, which textbook are you using, anyway? Someone here may be familiar with it, and be able to give specific advice. You mention that it was going very slowly; perhaps there was a reason for it. Otherwise, we may be able to recommend something better.

    I usually don't recommend C as a beginner's language; Python, IMAO, is much more suited for starting out. However, if you've already started with C, you might as well stick with it.
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in Short Understanding the C/C++ Preprocessor
    Taming Python A Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Mar 2004
    Posts
    855
    Rep Power
    1396
    @Schol-R-LEA

    Just a quick personal remark. I love C/C++ syntax and I have used many "C/C++ syntax" based languages but no matter how much I tried I was never able to get used to the Python syntax.

    Comments on this post

    • Schol-R-LEA agrees : Fair enough. No one language appeals to everyone.
    PHP Code:
    <?php
    abstract class Ignorance extends Stupidity implements Unavoidable 
         public static 
    $humiliation

         private function 
    __construct(){
            
    parent::__destruct();
         }; 

    ?>
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2010
    Posts
    6
    Rep Power
    0
    Thank you very much for the reply guys.

    @ clifford: I'm using Dev-C++ as my IDE, and the debugger didn't really detect any bugs in my code so far. If it had then I'd probably have had a better understanding of what I did wrong, and so may have been able to correct it myself.

    Thanks to kicken and holodoc for the radian conversion bit. Especially to kicken because he pointed a relatively simple procedure which I should have thought of. :chomp:

    @ Adak and Schol-R-LEA: I was using the "C for Dummies" book (because for, well, obvious reasons). The book got pretty boring to read after a while (I mean there's a whole chapter relating to comments FFS!). I was thinking of ASM as my starting language (y'know, the "how people learnt coding in the old days" logic :p), but the computer teacher at my school suggested C instead (said I am too young to start learning something like ASM). I wanted to learn a language that was as open-ended as it could get, i.e. machine/OS-independent. I'm learning this purely out of curiousity; I have no intention in making a career out of it (I'm not exactly very bright, so becoming a programmer would be a failure of a career for me :p)

    Anyway, yea I'll try continuing with the book before I code anything further. I guess some things just need to go at their own pace.
  26. #14
  27. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2009
    Posts
    194
    Rep Power
    76
    I'm not a big fan of the "for Dummies" books, in general. It does seem SLOW, but yeah - you need to hang in there with it.

    They aren't cheap, but if you get a copy of "The C Programming Language", second edition, by Kernighan and Ritchie, you will see the pace pick up like you can't believe! :eek:

    For a first time programmer, it's a real "OMG :confused: ?" experience. (In a great way if you love programming, though).

    You received good advice, imo. ASM is neat, but anything you do may not even run when the next generation of cpu's comes along. :chomp:

    I don't know you, but a first time program that deals with cosine and radians - I think you may be short changing yourself on the brightness scale, buddy.
    Last edited by Adak; September 2nd, 2010 at 11:09 PM.
  28. #15
  29. Lord of Dorkness
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2004
    Location
    Central New York. Texan via Arizona, out of his element!
    Posts
    8,524
    Rep Power
    3319
    A debugger doesn't detect bugs. It allows YOU to detect bugs. It does this by allowing you to step through the program, set breakpoints to halt execution, etc. That means you can inspect variables at various places to see if the program is doing what you expect.
    Functionality rules and clarity matters; if you can work a little elegance in there, you're stylin'.
    If you can't spell "u", "ur", and "ne1", why would I hire you? 300 baud modem? Forget I mentioned it.
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo