Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Where am I going wrong? C

Options
  • 05-10-2006 6:03pm
    #1
    Registered Users Posts: 9,847 ✭✭✭


    Hi folks,

    I am just starting out with C programming. I have created this simple program that calculates the average of 10 random numbers inputted by the user.

    It all seems to work ok but the answer comes out as a minus number.

    Here is the code:

    #include <stdio.h>

    int main()
    {
    int num1;
    int num2;
    int num3;
    int num4;
    int num5;
    int num6;
    int num7;
    int num8;
    int num9;
    int num10;
    int average;

    average = (num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10;

    printf("\n\nThis program will hopefully calculate the average of 10 randomly chosen numbers (integers) of your choice.\n\n");
    printf("Please enter the 1st number of your choice: ");
    scanf("%d", &num1);
    printf("\nNow enter the 2nd number of your choice: ");
    scanf("%d", &num2);
    printf("\nAnd now the 3rd number of your choice: ");
    scanf("%d", &num3);
    printf("\nAnd the 4th: ");
    scanf("%d", &num4);
    printf("\nThe 5th: ");
    scanf("%d", &num5);
    printf("\nThe 6th: ");
    scanf("%d", &num6);
    printf("\n7th: ");
    scanf("%d", &num7);
    printf("\n8th: ");
    scanf("%d", &num8);
    printf("\n9th: ");
    scanf("%d", &num9);
    printf("\nAnd last but not least your 10th number: ");
    scanf("%d", &num10);

    printf("\n\nThank you. The ten numbers you entered were:\n %d, %d, %d, %d, %d, %d, %d, %d, %d, %d", num1, num2, num3, num4, num5, num6, num7, num8, num9, num10);

    printf("\n\nThe average of these numbers is %d\n\n", average);
    return 0;
    }


    Perhaps its the data-type for my average variable?

    Thanks in advance for your help!


Comments

  • Closed Accounts Posts: 17,208 ✭✭✭✭aidan_walsh


    You're calculating the average of the numbers before either a) initialising the variable with a value, or b) reading in the users input.


  • Registered Users Posts: 9,847 ✭✭✭py2006


    You're calculating the average of the numbers before either a) initialising the variable with a value, or b) reading in the users input.

    Hmm, I don't think its either of them to be honest! The program does work as it compiles without any issues. It is just that that answer is -234332 or something like that which is wrong.


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    He's exactly write... you declared your variables. Then you calculated your average *then* you read in your 10 values. i.e. you calculate your average before you even know what values you're averaging. Its not a compile error, its a logic error.

    Move the average = ..... line to after your last scanf.

    Also, a nice way of inputing that amount of numbers would be to store them in an array.

    Try changing your program to read in 10 numbers, but instaed of saving them in 10 seperate variables, save each number into a position in an array.Then you can read in the 10 values in a nice simple for loop. Should reduce your lines of code by more than 70%.

    EDIT: Also, the "average" you compute is going to be wrong. It'll be the average, but rounded down to the nearest integer. If you want to be accurate to a few decimal places, declare average as a float and change your average = line to this...

    average = (num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10.0;

    or average = (num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/(float)10;

    If you dont do that, then because all your variables are integers, the sum will be computed using integer math, which will give something like 65/10 = 6; You want 65/10 = 6.5, so you have to force upcasting to a float using either of the two methods above.


  • Registered Users Posts: 9,847 ✭✭✭py2006


    He's exactly write... you declared your variables. Then you calculated your average *then* you read in your 10 values. i.e. you calculate your average before you even know what values you're averaging. Its not a compile error, its a logic error.

    Thanks for your response! Forgive my ignorance though as I am just learning this stuff!

    Surely I didn't calculate the average before the numbers were entered as in my last statement I am calculating the average:

    printf("\n\nThe average of these numbers is %d\n\n", average);

    It is only at this point that I bring in the average variable to calculate what numbers were entered???


  • Closed Accounts Posts: 17,208 ✭✭✭✭aidan_walsh


    Incorrect. You are calculating the average above, where you have your average = ... statement. What you are doing in printf is taking the value of that calculation, and substituting it in place of the %d type.


  • Advertisement
  • Registered Users Posts: 11,980 ✭✭✭✭Giblet


    Firstly, each of the variables aren't instansiated.

    eg:
    int num1 = 0; etc etc.

    That's why you are getting a value for average as the compiler will put in random numbers.

    Then the average should be calculated AFTER the numbers have been entered so it knows what numbers to use!


  • Registered Users Posts: 9,847 ✭✭✭py2006


    Incorrect. You are calculating the average above, where you have your average = ... statement. What you are doing in printf is taking the value of that calculation, and substituting it in place of the %d type.

    Oh ok, I thought all variables had to be declared and initialised at the start of the program. So your saying I can declare/initialise the average variable like this:

    printf("\n\nThank you. The ten numbers you entered were:\n %d, %d, %d, %d, %d, %d, %d, %d, %d, %d", num1, num2, num3, num4, num5, num6, num7, num8, num9, num10);

    float average;
    average = (num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10;
    printf("\n\nThe average of these numbers is %d\n\n", average);

    return 0;
    }


  • Closed Accounts Posts: 17,208 ✭✭✭✭aidan_walsh


    So your saying I can declare/initialise the average variable like this:
    No. Again, thats only reading the values of the variables and printing them. You still need to declare each variable as you are, and initialise them like Giblet said.


  • Registered Users Posts: 9,847 ✭✭✭py2006


    Giblet wrote:
    Firstly, each of the variables aren't instansiated.

    eg:
    int num1 = 0; etc etc.

    Surely I don't need to give each variable a value if that value will be coming from the user via the scanf function?


  • Registered Users Posts: 9,847 ✭✭✭py2006


    Oh the confusion! :confused:

    ok, think I have it now! I moved the line
    average = (num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10;
    and placed it below the last scanf!

    :D


  • Advertisement
  • Closed Accounts Posts: 583 ✭✭✭monkey tennis


    py2006 wrote:
    The program does work as it compiles without any issues.

    This is something you'd better get clear right off the bat - just because a C program compiles, doesn't in the slightest mean that it'll run the way you want/expect it to. C gives you a high degree of control over what happens in your program, but expects you to have the knowledge to use that control precisely. This makes it a pain in the ass to work with when you're starting off...
    py2006 wrote:
    Surely I don't need to give each variable a value if that value will be coming from the user via the scanf function?

    You don't have to, but it's good programming practice to always initialize your variables as you declare them - chances are one day you'll forget to initialize one before using it, causing unpredictable results.


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    #include <stdio.h>
     
    int main()
    {
       /* First we declare and initialise ALL variables. It's safest to ALWAYS initialise. */
     int num1=0;
     int num2=0;
     int num3=0;
     int num4=0;
     int num5=0;
     int num6=0;
     int num7=0;
     int num8=0;
     int num9=0;
     int num10=0;
     float average=0.0;
     
      // After all variables are declared and initialised, we take in our user input
      // And store it in each variable as required. 
     printf("\n\nThis program will hopefully calculate the average of 10 randomly chosen numbers (integers) of your choice.\n\n");
     printf("Please enter the 1st number of your choice: ");
     scanf("%d", &num1);
     printf("\nNow enter the 2nd number of your choice: ");
     scanf("%d", &num2);
     printf("\nAnd now the 3rd number of your choice: ");
     scanf("%d", &num3);
     printf("\nAnd the 4th: ");
     scanf("%d", &num4);
     printf("\nThe 5th: ");
     scanf("%d", &num5);
     printf("\nThe 6th: ");
     scanf("%d", &num6);
     printf("\n7th: ");
     scanf("%d", &num7);
     printf("\n8th: ");
     scanf("%d", &num8);
     printf("\n9th: ");
     scanf("%d", &num9);
     printf("\nAnd last but not least your 10th number: ");
     scanf("%d", &num10);
    
    
      // We now have all our input, and we print them out so the user can see
      // them again 
      printf("\n\nThank you.  The ten numbers you entered were:\n %d, %d, %d, %d, %d, %d, %d, %d, %d, %d", num1, num2, num3, num4, num5, num6, num7, num8, num9, num10); 
    
      // Now we calculate the average. As soon as this line is reached, the
      // additions and divisions are performed and the result stored in the
      // variable called "average". Note that i divide by '10.0' and not '10'.
      // Experiment with dividing by just 10 and you'll see why i did that.
      average = (num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10.0;
    
      // Now that the result is calculated and stored, we can print it out at
      // any time, or use it in further calculations. In this case, we're just printing
      // it out. Notice that i've used printf("...%f") as average is now a FLOAT.
      printf("\n\nThe average of these numbers is %f\n\n", average);
     return 0;
    }
    

    There ya go, nice and commented. Hopefully it'll make sense to ya.
    Surely I don't need to give each variable a value if that value will be coming from the user via the scanf function?
    Thing is that one day you will forget to initialise a variable unless you get into the habit of it. If that happens, you'll get unpredictable behaviour. The amount of times i've tracked a bug in someones assignment that was due to a variable not being initialised/set up correctly is unbelievable. If you initialise every variable to 0, then usually you can avoid a whole host of problems and often makes it easier to spot a bug. Especially when performing maths.


  • Registered Users Posts: 919 ✭✭✭timeout


    Are you learning from a programming book? Best way really, unless you got someone teaching you.


  • Registered Users Posts: 9,847 ✭✭✭py2006


    This is something you'd better get clear right off the bat - just because a C program compiles, doesn't in the slightest mean that it'll run the way you want/expect it to. C gives you a high degree of control over what happens in your program, but expects you to have the knowledge to use that control precisely. This makes it a pain in the ass to work with when you're starting off...



    You don't have to, but it's good programming practice to always initialize your variables as you declare them - chances are one day you'll forget to initialize one before using it, causing unpredictable results.

    Ok, cool! Thanks for the advice! What should I initialise them with in this case? Is there like a dummy value you can use? or does it matter at all?


  • Registered Users Posts: 9,847 ✭✭✭py2006


    #include <stdio.h>
     
    int main()
    {
       /* First we declare and initialise ALL variables. It's safest to ALWAYS initialise. */
     int num1=0;
     int num2=0;
     int num3=0;
     int num4=0;
     int num5=0;
     int num6=0;
     int num7=0;
     int num8=0;
     int num9=0;
     int num10=0;
     float average=0.0;
     
      // After all variables are declared and initialised, we take in our user input
      // And store it in each variable as required. 
     printf("\n\nThis program will hopefully calculate the average of 10 randomly chosen numbers (integers) of your choice.\n\n");
     printf("Please enter the 1st number of your choice: ");
     scanf("%d", &num1);
     printf("\nNow enter the 2nd number of your choice: ");
     scanf("%d", &num2);
     printf("\nAnd now the 3rd number of your choice: ");
     scanf("%d", &num3);
     printf("\nAnd the 4th: ");
     scanf("%d", &num4);
     printf("\nThe 5th: ");
     scanf("%d", &num5);
     printf("\nThe 6th: ");
     scanf("%d", &num6);
     printf("\n7th: ");
     scanf("%d", &num7);
     printf("\n8th: ");
     scanf("%d", &num8);
     printf("\n9th: ");
     scanf("%d", &num9);
     printf("\nAnd last but not least your 10th number: ");
     scanf("%d", &num10);
     
     
      // We now have all our input, and we print them out so the user can see
      // them again 
      printf("\n\nThank you.  The ten numbers you entered were:\n %d, %d, %d, %d, %d, %d, %d, %d, %d, %d", num1, num2, num3, num4, num5, num6, num7, num8, num9, num10); 
     
      // Now we calculate the average. As soon as this line is reached, the
      // additions and divisions are performed and the result stored in the
      // variable called "average". Note that i divide by '10.0' and not '10'.
      // Experiment with dividing by just 10 and you'll see why i did that.
      average = (num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10.0;
     
      // Now that the result is calculated and stored, we can print it out at
      // any time, or use it in further calculations. In this case, we're just printing
      // it out. Notice that i've used printf("...%f") as average is now a FLOAT.
      printf("\n\nThe average of these numbers is %f\n\n", average);
     return 0;
    }
    

    There ya go, nice and commented. Hopefully it'll make sense to ya.

    Wow, thanks a million for that mutant!


  • Registered Users Posts: 9,847 ✭✭✭py2006


    timeout wrote:
    Are you learning from a programming book? Best way really, unless you got someone teaching you.

    Well yea I am. I am learning in in college at night aswell but I am a bit behind so I am going through the book too.


  • Registered Users Posts: 11,980 ✭✭✭✭Giblet


    Initialize to either 0 or null (null would be used for strings rather than 0)
    string myString = null;
    int myInt= 0;


  • Registered Users Posts: 9,847 ✭✭✭py2006


    Giblet wrote:
    Initialize to either 0 or null (null would be used for strings rather than 0)
    string myString = null;
    int myInt= 0;

    Ok, I did that!

    I also managed to declare and initalise all variables on the one line like below.

    int num1, num2, num3, num4, num5, num6, num7, num8, num9, num10 = 0;


  • Closed Accounts Posts: 17,208 ✭✭✭✭aidan_walsh


    py2006 wrote:
    Ok, I did that!

    I also managed to declare and initalise all variables on the one line like below.

    int num1, num2, num3, num4, num5, num6, num7, num8, num9, num10 = 0;
    That only initialises the last variable, not all 10 of them.


  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    What aidan_walsh said.

    Having just decided to learn C after reading this thread:
    int num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0, num7 = 0, num8 = 0, num9 = 0, num10 = 0;
    
    


  • Advertisement
  • Registered Users Posts: 9,847 ✭✭✭py2006


    Oh ok, I changed it back! Thanks a mil!


  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    No problem, presumably its working now?


  • Registered Users Posts: 9,847 ✭✭✭py2006


    No problem, presumably its working now?

    Yep, working fine now thanks!

    My next project is to work on a little program that will calculate the take home pay of a user who inputs their gross pay.

    It will have to perform a calculation based on what they earn. ie a seperate calculation to be used for the higher tax bracket and the lower tax bracket.

    I presume it will involve using IF and ELSE statements which I haven't really look at yet.


  • Closed Accounts Posts: 8,866 ✭✭✭Adam


    As I said earlier I decided to learn C last night, I found this site: http://www.eskimo.com/%7escs/cclass/notes/top.html

    Bascally its a step by step introduction to C, and I found it immensely readable and informative, I spent about 3 hours reading through the pages sequentially and feel I've learned a great deal and highly recommend them to you.

    EDIT: Yes, that program will revolve around an if... else statement, and shouldnt be too complicated at all.


  • Registered Users Posts: 9,847 ✭✭✭py2006


    As I said earlier I decided to learn C last night, I found this site: http://www.eskimo.com/%7escs/cclass/notes/top.html

    Bascally its a step by step introduction to C, and I found it immensely readable and informative, I spent about 3 hours reading through the pages sequentially and feel I've learned a great deal and highly recommend them to you.

    Great stuff. Although, I find it hard to read long passages of text off a computer screen. I prefer a book.

    Apparently its a good programming language to start out on. And jumping to another language afterwards is supposed to be easy enough.

    In college, we were recommended to get "A Guide to C Programming" by Paul Kelly! I found it a bit hard to follow at first as I think you would have to have a basic understanding of programming prior to getting it. I believe the person who wrote it was a lecturer there, hence the recommendation. :rolleyes:

    So I also bought "C Programming - In Easy Steps" which is excellent! This book explains things better so I now jump between books as I go.


  • Registered Users Posts: 26,578 ✭✭✭✭Creamy Goodness


    py2006 wrote:
    In college, we were recommended to get "A Guide to C Programming" by Paul Kelly! I found it a bit hard to follow at first as I think you would have to have a basic understanding of programming prior to getting it. I believe the person who wrote it was a lecturer there, hence the recommendation. :rolleyes:

    i found that too with this book, but it gets more easier to understand in the later stages as it's good at describing the likes or arrays/pointers/structures which you'll come across soon enough. it also helps when i have him as a lecturer aswell :p


  • Registered Users Posts: 1,996 ✭✭✭lynchie


    Cremo wrote:
    i found that too with this book, but it gets more easier to understand in the later stages as it's good at describing the likes or arrays/pointers/structures which you'll come across soon enough. it also helps when i have him as a lecturer aswell :p

    He was a cnut of a lecturer. Never bought his book either even though he wanted every1 to buy it..


Advertisement