Thread: Beginner: having problem with "simple" arithmetic program

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    2

    Beginner: having problem with "simple" arithmetic program

    Hi all,

    I am a rank beginner to programming and have been following along to a couple of tutorials. I feel like I have a decent grip on the basics and decided to go solo and attempt a very simple program.
    What I thought I would do is create a program to calculate batting average. Simple right? hits/at bats. Well I get no errors when compiling but it just doesn't calculate properly. I'm guessing it has something to do with the at-bats being the larger number. Any tips or pointers would be much appreciated, and here is the code (please be kind!) that I've written
    Thanks
    Mike
    Code:
    
    #include <stdio.h>
    #include <conio.h>
    
    
    
    int main()
    {
      int hits;
      int atbats;
      float bavg;
        
      scanf("%d%d", &hits, &atbats);
      
      bavg = hits/atbats;
      
      printf("%f", bavg);
        
        getch();
        return 0;
        
        }

  2. #2
    Webhead Spidey's Avatar
    Join Date
    Jul 2009
    Posts
    285
    Since both you hits and atbats variables are declared as ints, bavg = hits/atbats will result in integer division, truncating any decimal value. Even thogh the bavg is declared as a float it will get assigned the truncated value. So, you want to declare your hits and atbats as floats and read them in using %f.
    Spidey out!

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    2
    Thank you Spidey. I tried that and it worked perfectly. I was on the right track as at one point I declared them all as floats but that was before I learned about %f.
    Boy I've got a lot to learn but this is so much fun, I can't wait to try learn something new.

    Thanks again.
    Mike.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem w/ doubles in friend's program
    By mkylman in forum C Programming
    Replies: 16
    Last Post: 11-22-2008, 10:45 AM
  2. Problem with my program i cant figure out...
    By youareafever in forum C Programming
    Replies: 7
    Last Post: 11-01-2008, 11:56 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. simple frontend program problem
    By gandalf_bar in forum Linux Programming
    Replies: 16
    Last Post: 04-22-2004, 06:33 AM
  5. Console Program Problem
    By Breach23 in forum C++ Programming
    Replies: 3
    Last Post: 10-19-2001, 12:35 AM