Thread: Need someone to check my code

  1. #1
    Registered User Stormboy's Avatar
    Join Date
    Aug 2013
    Location
    Planet Earth
    Posts
    12

    Need someone to check my code

    Hi,
    I solved the 1st problem on CProgramming. However, when I checked the solution, it was very much different from my code. When I run my program it gives the expected result all right. So, I need someone to check my code and see if it can be considered the 'correct' solution to the problem. Also, can you please tell me the parts of my code that I can improve?
    (Note: I am new to C. Just started it a while ago.)

    Code:
    Code:
    #include <stdio.h>
    
    //Function that converts from degreeCelsius to degreeFahrenheit
    float convert_to_degf(float deg_c)
    {
        float result = ((deg_c*9)/5)+32;
        return result;
    }
    //The main function
    int main()
    {
        //Variable declarations
        int low_lim = -1;
        int high_lim = -1;
        int step = -1;
        float result;
        //Get the lower limit from user. Repeat if not within the range.
        while(low_lim < 0)
        {
            printf("Please give in a lower limit, limit >= 0: ");
            scanf("%d", &low_lim);
        }
        //Get the higher limit from the user. Repeat if not within the range.
        while(high_lim <= low_lim || high_lim > 50000)
        {
            printf("Please give in a higher limit, %d < limit <= 50000: ", low_lim);
            scanf("%d", &high_lim);
        }
        //Get the step from the user. Repeat if not within the range. 
        while(step < 0 || step > high_lim-low_lim)
        {
            printf("Please give in a step, 0 < step <= %d: ", high_lim-low_lim);
            scanf("%d", &step);
        }
        //Prints the table headings.
        printf("\nCelsius               Fahrenheit\n");
        printf("-------               ----------\n");
        //Print the values till the next value is greater than the high limit.
        while(1)
        {
            result = convert_to_degf(low_lim);
            printf("%d.000000             %f\n", low_lim, result);
            if(low_lim+step <= high_lim)
            {
                low_lim += step;
            }
            else
            {
                break;
            }
        }
        //Wait for user to press a key
        getch();
        return 0;
    }
    Thanks.
    Attached Files Attached Files

  2. #2
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688
    If the solution is correct, (i.e you get the expected output) then the program works as it is supposed to.

    The thing about programming in general is, a solution to a problem can be written various ways. Even the simplest
    problem can have either a huge complex answer (in code), or a very small segment of code that does the same
    thing as the very large piece of code = it gets the result the programmer wanted. The main point here is personal
    style. Some people will look at the code and think - "hey thats a good way to find the solution!" another person might
    look at the same code and say "Thats good and it works - but there is a more effiecient way to get that result, if you
    did x, y, z"

    Again, it does depend on the general knowledge of C from the programmer and the skills he/she has learned to that point.
    Most programs can be re-visited when more advanced features are learnt, and programs can be improved in places or
    in some cases, totally re-written. Just my two cents.

    The bottom line is - if it works, and your happy with it - it's fine. If the compiler moans or your not happy, change it.
    Double Helix STL

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Some things I consider to be wrong:
    * low_lim should be allowed to be below zero (I know the problem says >= 0, but that's just stupid for temperatures)
    * if you're limiting the upper value of high_lim then surely low_lim must be below that too
    * the step shouldn't be allowed to be 0

    Your constants for the upper and lower limit should be defines.
    (The constants in your equation should NOT be defines though.)

    Your main loop is not well written. More idiomatic is:
    Code:
    for (t = low_lim; t <= high_lim; t += step)
        printf("%6d          %8.1f\n", t, convert_to_degf(t));
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  4. #4
    Registered User Stormboy's Avatar
    Join Date
    Aug 2013
    Location
    Planet Earth
    Posts
    12
    Thanks for the replies . I really appreciate it. I've changed my code a bit according what oogabooga said.
    Here it is:
    Code:
    #include <stdio.h>
    #define absolute_zero -273
    #define max_lim 50000
    
    //Function that converts from degreeCelsius to degreeFahrenheit
    float convert_to_degf(float deg_c)
    {
        float result = ((deg_c*9)/5)+32;
        return result;
    }
    //The main function
    int main()
    {
        //Variable declarations
        float low_lim = -274.000000;
        float high_lim = -275.000000;
        int step = -1;
        float i;
        float result;
        //Get the lower limit from user. Repeat if not within the range.
        while(low_lim < absolute_zero)
        {
            printf("Please give in a lower limit, limit >= %d: ", absolute_zero);
            scanf("%f", &low_lim);
        }
        //Get the higher limit from the user. Repeat if not within the range.
        while(high_lim <= low_lim || high_lim > max_lim)
        {
            printf("Please give in a higher limit, %.1f < limit <= 50000: ", low_lim);
            scanf("%f", &high_lim);
        }
        //Get the step from the user. Repeat if not within the range. 
        while(step <= 0 || step > high_lim-low_lim)
        {
            printf("Please give in a step, 0 < step <= %.1f: ", high_lim-low_lim);
            scanf("%d", &step);
        }
        //Prints the table headings.
        printf("\nCelsius             Fahrenheit\n");
        printf("-------             ----------\n");
        //Print the values till the next value is greater than the high limit.
        for(i = low_lim; i <= high_lim; i += step)
        {
            result = convert_to_degf(i);
            printf("%f           %f\n", i, result);
        }
        //Wait for user to press a key
        getch();
        return 0;
    }
    Last edited by Stormboy; 08-28-2013 at 01:31 PM.

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    The new version looks much better. A few other notes, mostly stylistic issues:

    • As a convention, names of constants and #defines are usually ALL_CAPS, which makes for a nice visual reminder that it's a constant/#define when reading & maintaining code. Readability and maintainability is of utmost importance as your projects grow larger.
    • I would use doubles instead of floats, they're much more precise. I only use floats if I absolutely have to, e.g. for size reasons, which is rare.
    • Since you made absolute_zero a constant, it would make more sense to initialize low_limit to absolute_zero-1 and high_limit to low_limit-1, so if you change absolute_zero your loops would still work. That's not a real issue here (the only change to absolue_zero might be to make it -273.15, which would still let your input loops run), but it would better convey the intention of the code. I.e. the code is setting low_lim to a value below absolute_zero and high_lim to a value below low_lim, so your loops will not be skipped. There is a better way though: use a do-while loop. Then you don't need to worry about initial values for your user input variables. The loop condition is checked after the loop body is executed, so the variable has the value the user input, and you don't need to worry about giving it the right initial value (this is more beneficial if you ever end up changing the loop condition significantly). Also, they are guaranteed to run at least once, which is good since you always want to ask the user at least once for input, and only repeat if it's invalid.
    • You should get in the habit of checking return codes of functions, in particular IO functions (user, file, network, etc) like scanf. It should return the number of values read. If it's not what you were expecting (1 in each of your cases, for the single %f/%d in each call), handle the error and stop or retry as appropriate.
    • You may want to clear the input buffer after each scanf call. If the user accidentally inputs some letters, your loop may get stuck. There's an example here: FAQ > Flush the input buffer - Cprogramming.com. The key part is that while (getchar()) loop, which, if you put into a function (e.g. called flush_input_buffer()), make a nice one-line way to clear the input buffer.
    • If you expect a user to press a key to continue/terminate the application, it's nice to inform them. Sure, they'll probably hit one anyway, but best be safe. Also, if all you're doing there is trying to keep your IDE from closing the program before you can read the output, there are better ways, that don't annoy regular terminal users (like me).

  6. #6
    Registered User Stormboy's Avatar
    Join Date
    Aug 2013
    Location
    Planet Earth
    Posts
    12
    Quote Originally Posted by anduril462 View Post
    The new version looks much better. A few other notes, mostly stylistic issues:

    • As a convention, names of constants and #defines are usually ALL_CAPS, which makes for a nice visual reminder that it's a constant/#define when reading & maintaining code. Readability and maintainability is of utmost importance as your projects grow larger.
    • I would use doubles instead of floats, they're much more precise. I only use floats if I absolutely have to, e.g. for size reasons, which is rare.
    • Since you made absolute_zero a constant, it would make more sense to initialize low_limit to absolute_zero-1 and high_limit to low_limit-1, so if you change absolute_zero your loops would still work. That's not a real issue here (the only change to absolue_zero might be to make it -273.15, which would still let your input loops run), but it would better convey the intention of the code. I.e. the code is setting low_lim to a value below absolute_zero and high_lim to a value below low_lim, so your loops will not be skipped. There is a better way though: use a do-while loop. Then you don't need to worry about initial values for your user input variables. The loop condition is checked after the loop body is executed, so the variable has the value the user input, and you don't need to worry about giving it the right initial value (this is more beneficial if you ever end up changing the loop condition significantly). Also, they are guaranteed to run at least once, which is good since you always want to ask the user at least once for input, and only repeat if it's invalid.
    • You should get in the habit of checking return codes of functions, in particular IO functions (user, file, network, etc) like scanf. It should return the number of values read. If it's not what you were expecting (1 in each of your cases, for the single %f/%d in each call), handle the error and stop or retry as appropriate.
    • You may want to clear the input buffer after each scanf call. If the user accidentally inputs some letters, your loop may get stuck. There's an example here: FAQ > Flush the input buffer - Cprogramming.com. The key part is that while (getchar()) loop, which, if you put into a function (e.g. called flush_input_buffer()), make a nice one-line way to clear the input buffer.
    • If you expect a user to press a key to continue/terminate the application, it's nice to inform them. Sure, they'll probably hit one anyway, but best be safe. Also, if all you're doing there is trying to keep your IDE from closing the program before you can read the output, there are better ways, that don't annoy regular terminal users (like me).
    Thanks for the tips. I'll keep them in mind .

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Check my code.
    By Mr.Lnx in forum C Programming
    Replies: 10
    Last Post: 10-19-2012, 03:59 PM
  2. Help! Check my code over.
    By omGeeK in forum C Programming
    Replies: 6
    Last Post: 11-04-2010, 11:34 PM
  3. check this code out
    By debuger2004 in forum C Programming
    Replies: 25
    Last Post: 06-21-2003, 12:24 PM
  4. check out this code
    By brutal in forum C Programming
    Replies: 8
    Last Post: 05-21-2002, 10:38 PM
  5. Can anyone check this code
    By a_learner in forum C Programming
    Replies: 5
    Last Post: 10-06-2001, 02:41 PM

Tags for this Thread