Thread: Why doesn't this (relatively simple) code work? (aka, why does my computer hate me?)

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    5

    Why doesn't this (relatively simple) code work? (aka, why does my computer hate me?)

    Hey, I'm building a small program.
    This is just the first part, which tries to scan for a multi-digit number and put it in some variable.
    Problem is, for some reason, it wouldn't calculate simple things (sometimes even doing 10^3, 10^1 and 10^0 just fine, but giving 99 as a result of 10^2. Yes, "wtf" did come to mind at this point).

    Is this a problem with the code or it is my computer trying to annoy it's wretched master?
    Help would be REALLY appreciated.
    Here's the code:
    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <math.h>
    
    void main()
    {
    int y=1,ss=0,fatty;
    char ch=0;
    char num[4]={{0,0,0,0}};
    char number=0;
    int tester;
    
    printf("Enter your number. When you're done, press esc.");
    
    while (y<2)
    {
    
        ch=getch();
        if (ch==27)
           y = 2;
        else
        {
            if (ch > 47 && ch < 58)
            {
                   
                ch = ch - 48;
                printf("%d\n",ch);
                num[ss]=ch;
                ss++;
            }
        }
    
    }
    ss--;
    
    for ( fatty = 0 ; fatty <= ss ; fatty++ )
    {
        tester = pow(10,ss-fatty);
        printf("\n%d,%d,%d,%d",ss,ss-fatty,num[ss-fatty],pow(10,num[ss-fatty]));
    
        getch();
        number = number + num[ss-fatty] * pow(10,num[ss-fatty]) ;
        printf("\n%lf",number);
    }
    
    printf("Your number is: %lf",number);
    getch();
    
    
    }
    This version is closer to working, though it uses %d when trying to printf a double variable, instead of %lf (which I think is correct).

    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <math.h>
    
    void main()
    {
    int y=1,ss=0,fatty;
    char ch=0;
    char num[4]={{0,0,0,0}};
    char number=0;
    int tester;
    
    printf("Enter your number. When you're done, press esc.");
    
    while (y<2)
    {
    
        ch=getch();
        if (ch==27)
           y = 2;
        else
        {
        ch = ch - 48;
        printf("%d\n",ch);
        num[ss]=ch;
        ss++;
        }
    
    }
    ss--;
    
    for ( fatty = 0 ; fatty <= ss ; fatty++ )
    {
        tester = pow(10,ss-fatty);
        printf("%d,%d,%d,%d",ss,ss-fatty,num[ss-fatty],tester);
    
        getch();
        number = number + num[ss-fatty] * tester ;
        printf("\n%d",number);
    }
    
    printf("Your number is: %lf",number);
    getch();
    
    
    }

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    • It should be "int main(void)" not "void main()".
    • Stop guessing at the printf format specifers. &#37;d for ints, and %f for doubles and floats.
    • Try to indent a little better. Everything should not be smacked up against the left margin.
    • Don't use conio.h and getch() if you don't have to. They are not portable, which means they can't be used on every system.

  3. #3
    Registered User
    Join Date
    May 2007
    Posts
    5
    Quote Originally Posted by MacGyver View Post
    • It should be "int main(void)" not "void main()".
    • Stop guessing at the printf format specifers. %d for ints, and %f for doubles and floats.
    • Try to indent a little better. Everything should not be smacked up against the left margin.
    • Don't use conio.h and getch() if you don't have to. They are not portable, which means they can't be used on every system.
    1. Care to explain why? That's what I was taught, and it never gave me problems.
    2. Not guessing, I know that, but for some reason it makes a little more sense if I put a %d in the double printfs. The first code is correct in that way, if I'm not mistaken.
    3. I don't see a problem with my indenting?
    4. I'm only planning to use it on my pc. Where is it unusable? And what can I use instead?
    5. No comments about the code itself? :|

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Quote Originally Posted by tima View Post
    1. Care to explain why? That's what I was taught, and it never gave me problems.
    It's not the C standard. Every C standard has always said that main() returns an int. Allowing main() to return void is something that various compilers allow, but it is not legal C.

    I've written posts on this subject and how a value will be returned, even if you write main() to return void. Because of this, efforts to debug your program later on could prove very annoying in the future when you need to analyze the return value to detect if the program succeeded or not.

    Quote Originally Posted by tima View Post
    2. Not guessing, I know that, but for some reason it makes a little more sense if I put a %d in the double printfs. The first code is correct in that way, if I'm not mistaken.
    Speaking of printf format specifers, %lf is not used either, although it's recognized by many compilers. %lf is used, however, in calls to scanf().

    Quote Originally Posted by tima View Post
    3. I don't see a problem with my indenting?
    Is that a question or a statement?

    Indenting properly makes your code easier to read, and therefore, easier to debug, analyze, maintain, correct, etc. etc..

    Quote Originally Posted by tima View Post
    4. I'm only planning to use it on my pc. Where is it unusable? And what can I use instead?
    conio.h is an older header file, usually included with Borland's compilers I believe.

    If you want it that badly, then whatever. I'm just warning not to expect it to work on other compilers/systems.

    Quote Originally Posted by tima View Post
    5. No comments about the code itself? :|
    Not really.

    Actually, here's a few:

    • getchar() returns an int, not a char. Make ch an int. This is needed because of EOF.
    • You should have a limit to make sure the user doesn't enter more numbers than your array can hold.
    • pow() returns a double, not an int. I wouldn't try forcing it to write to an int.


    I would recommend you turn up the warning level of your compiler.

  5. #5
    Registered User
    Join Date
    May 2007
    Posts
    5
    Quote Originally Posted by MacGyver View Post
    It's not the C standard. Every C standard has always said that main() returns an int. Allowing main() to return void is something that various compilers allow, but it is not legal C.

    I've written posts on this subject and how a value will be returned, even if you write main() to return void. Because of this, efforts to debug your program later on could prove very annoying in the future when you need to analyze the return value to detect if the program succeeded or not.



    Speaking of printf format specifers, %lf is not used either, although it's recognized by many compilers. %lf is used, however, in calls to scanf().



    Is that a question or a statement?

    Indenting properly makes your code easier to read, and therefore, easier to debug, analyze, maintain, correct, etc. etc..



    conio.h is an older header file, usually included with Borland's compilers I believe.

    If you want it that badly, then whatever. I'm just warning not to expect it to work on other compilers/systems.



    Not really.

    Actually, here's a few:

    • getchar() returns an int, not a char. Make ch an int. This is needed because of EOF.
    • You should have a limit to make sure the user doesn't enter more numbers than your array can hold.
    • pow() returns a double, not an int. I wouldn't try forcing it to write to an int.


    I would recommend you turn up the warning level of your compiler.
    - Alright, I'll change the void thing and the specifier. See I learned this at school from a really incompetent teacher, so I've got some holes in my knowledge.
    - The indent thing was basicly "I don't see a problem with my indenting, what it the problem?"
    The way I indented looks pretty good and readable to me. If you could tell me what you think is wrong, that'd be nice.
    - What can I use instead of conio.h and getch()?

    About the comments:
    - Again, something I've been taught at school. I'll start using int's. What's EOF?
    - I'm the only one that'll use this one, I'm programming it for my own fun, so that isn't gonna be a problem. I do put limits when I make programs for other people.
    - So should I change like four int's to doubles for that?


    Edit: That fixed it, thanks a lot. Though I would appreciate it if you would answer the above questions anyway
    Also: Is there any way I can make it just show the number, without so many decimal points afterwards? (eg, 321 instead of 321.000000000)

    Thanks, tima.

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Quote Originally Posted by tima View Post
    - Alright, I'll change the void thing and the specifier. See I learned this at school from a really incompetent teacher, so I've got some holes in my knowledge.
    The problem with various courses is that some teachers don't teach C. They teach the variation of C that is based upon one specific compiler. I think that's a bad idea. Sure, it's fine to know what compilers support what extra features, and if you feel you need to use them in some cases, whatever. The bad thing is getting dependent on compiler-specific features, or thinking that it's going to work the same for all C compilers.

    One example is the call fflush(stdin). On some compilers, it works one way, and many people expect it to work the same way on every compiler. The problem is that the C standard says that such behavior is undefined, which means that any compiler can do anything when that happens, which means it may or may not work the way you think it will.

    This is why if you're used to writing code that is 100&#37; acceptable C, you will have less headaches when you use a compiler that is either less forgiving or closer to the standard.

    Quote Originally Posted by tima View Post
    - The indent thing was basicly "I don't see a problem with my indenting, what it the problem?"
    The way I indented looks pretty good and readable to me. If you could tell me what you think is wrong, that'd be nice.
    One thing I thought right away could use some work was that you have some of your lines against the left margin. I thought those could afford to be indented.

    Quote Originally Posted by tima View Post
    - What can I use instead of conio.h and getch()?
    This is a common question. I could go into detailed explanation, but this should be saved for another discussion. Simple answer: http://faq.cprogramming.com/cgi-bin/...&id=1043284385

    conio.h + getch() is listed in there, but as is warned, it's not portable.

    Quote Originally Posted by tima View Post
    About the comments:
    - Again, something I've been taught at school. I'll start using int's. What's EOF?
    EOF is a value that stands for End Of File. You can tell when the end of the stream is reached when that char is read (more or less.... this gets a little more complicated with files and such). If you try to read EOF into a char, you're in a position to start getting some odd behavior that won't make sense.

    Quote Originally Posted by tima View Post
    - I'm the only one that'll use this one, I'm programming it for my own fun, so that isn't gonna be a problem. I do put limits when I make programs for other people.
    In all honesty, you should get into the habbit of it now imo. Errors like this enable takeovers of your program, and the like. Getting into a routine of always making sure you write safe code helps you later on when you have to write something that won't be in a sandbox environment.

    Quote Originally Posted by tima View Post
    Also: Is there any way I can make it just show the number, without so many decimal points afterwards? (eg, 321 instead of 321.000000000)
    Look up the printf() specifiers. You do it with the %f flag and putting a number inside of it.

  7. #7
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by tima View Post
    1. Care to explain why? That's what I was taught, and it never gave me problems.
    I know a guy who drives around without a seatbelt. It's never given him any problems...

    2. Not guessing, I know that, but for some reason it makes a little more sense if I put a %d in the double printfs.
    It may "make sense" to you but it's wrong. The "d" in %d means "decimal," and it's used to print integers in decimal format.

    3. I don't see a problem with my indenting?
    Most people indent the body of a function from the left margin. However, I have seen code where functions begin at column 0. I think a lot of people would complain about it, but technically it's okay, so long as you're consistent.

    4. I'm only planning to use it on my pc. Where is it unusable? And what can I use instead?
    It's unusable everywhere BUT a PC with a very particular compiler. In other words, most of the computers in the world. Use fgetc() or something similar.

    A lot of so called "teachers" are full of crap. I'm sorry to see you've been taught by somebody who's clueless. Unfortunately, as a new programmer you have no way of knowing who is knowledgeable and who isn't, so that's not your fault.

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Just to be clear about format specifiers:
    • ints: &#37;d or %i (they are equivalent)
    • floats: %f
    • doubles:
      • for printf(): %f
      • for scanf(): %lf
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    &#37;d and %i are the same only when it comes to printf(). They are different for scanf().

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Wow, you're right! I didn't know that, believe it or not.
    d
    Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of strtol() with the value 10 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to int.
    i
    Matches an optionally signed integer, whose format is the same as expected for the subject sequence of strtol() with 0 for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer to int.
    From http://www.opengroup.org/onlinepubs/...ons/scanf.html
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem in simple code.
    By richdb in forum C Programming
    Replies: 6
    Last Post: 03-20-2006, 02:45 AM
  2. Audit this simple code?
    By xconspirisist in forum C++ Programming
    Replies: 1
    Last Post: 02-09-2006, 07:08 AM
  3. Simple C++ question. Error in code somewhere.
    By Paracropolis in forum C++ Programming
    Replies: 10
    Last Post: 02-06-2006, 08:59 AM
  4. Tabbed Windows with MDI?
    By willc0de4food in forum Windows Programming
    Replies: 25
    Last Post: 05-19-2005, 10:58 PM
  5. Anybody fix this simple code?
    By Killinger in forum C++ Programming
    Replies: 25
    Last Post: 08-09-2004, 01:53 PM