trying to do simple math with float and int type

This is a discussion on trying to do simple math with float and int type within the C Programming forums, part of the General Programming Boards category; I'm trying to learn by doing. I have written some code below and it's not outputting the way I expected ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    13

    trying to do simple math with float and int type

    I'm trying to learn by doing. I have written some code below and it's not outputting the way I expected it to. Once I get this piece working I'd like to add code to round the numbers so that there are only 2 to 3 decimal places.

    the step after that would be to add code so that I can leave z as an int type and then change it's type in function div()

    if you could help out I'd really appreciate it, also if you have any suggestions or areas where I could potentially be shooting myself in the foot I'd appreciate the feedback as well


    my code looks like this:

    Code:
    #include <stdio.h>
    
    int x,y;
    float z,a;
    
    int mult(int x,int y);
    float div(int x,int y);
    
    int main()
    {
    	printf("\nPlease enter a number: ");
    	scanf("%d",&x);
    	printf("\nPlease enter a second number: ");
    	scanf("%d",&y);
    	
    	a=mult(x,y);
    	printf("\n%d times %d equals %f",x,y,a);
    
    	printf("\nand");
    	
    	a=div(x,y);
    	printf("\n%d divided by %d equals %f",x,y,a);
    	
    	printf("\nHave a nice Day!!!\n");
    	
    	
    	
    	
    	
    	return 0;
    }
    
    
    
    int mult(int x,int y)
    {
    	z=x*y;
    	return z;
    }
    
    float div(int x,int y)
    {
    	z=x/y;
    	return z;
    }
    and the output looks like this

    Code:
    Please enter a number: 5
    
    Please enter a second number: 4
    
    5 times 4 equals 20.000000
    and
    5 divided by 4 equals 1.000000
    Have a nice Day!!!
    I'm trying to allow variables 5 and 4 to be integers and z and a to be float. I expect the output to look like this

    Code:
    Please enter a number: 5
    
    Please enter a second number: 4
    
    5 times 4 equals 20.000000
    and
    5 divided by 4 equals 1.250000
    Have a nice Day!!!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    The catch is that 5/4 actually is 1 (well, 1 remainder 1, but you didn't ask for the remainder part). If you cast the numbers to float, and then divide, good things may happen.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,053
    Use double instead of int.

    For rounding, I believe there is a way to specify the number of digits after the decimal place. Something like "&#37;.2f".
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by King Mir View Post
    Use double instead of int.

    For rounding, I believe there is a way to specify the number of digits after the decimal place. Something like "%.2f".
    Float will also work perfectly fine. Double gives about 15 digits in the result, float about 8.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Sep 2008
    Posts
    13
    do I need to cast x and y as float type to get the decimal place?

  6. #6
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    Why are you working with global variables?
    and yes - to make float division you need to cast at least one of operands to float before you divide
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  7. #7
    Registered User
    Join Date
    Sep 2008
    Posts
    13
    Quote Originally Posted by vart View Post
    Why are you working with global variables?
    and yes - to make float division you need to cast at least one of operands to float before you divide
    because I don't know any better, this is really like my first attempt at a program all on my own.

    The biggest problem I am having is variables act differently depending on how you save them with the %d, %f etc. its pretty annoying because I'm not 100% with what I'm doing and the limitations yet.

    can anyone point me to a good example of casting?
    also how do I limit decimal places on a float type variable?

    thanks

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    1. Something like (float)x/(float)y is probably literally the only good example of casting that there is, since by the time you reach the level where you need some other form of casting you'll already have all the skills. And for that matter, this cast is unnecessary too: I usually do x*1.0/y which does the same thing.
    2. What do you mean by "limit decimal places"? If you mean when printing the number out, then at some point you need to actually read the section on printf in your C book, or type "man printf" at your terminal/web browser. If you mean when storing the number, then there is of course no such thing (all floats are going to use the same amount of space internally no matter what).

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I usually do x*1.0/y
    There is no guarantee that the compiler optimizes this to the same as (float)x/(float)y, since it may decide that multiplying by 1.0 and dividing by y is NECESSARY to keep to what you wanted to have happen. Yes, I know, it's also quite likely that the compiler WILL optimize it - but stranger things have happened. [I tried in gcc, and the only difference between the two variants was that the second form does the divide the other way around - loads the second number first and divides "backwards" using fdivrp - but that shows that the code generation is done differently, and that the optimization stage is responsible for removing the 1.0].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,904
    Quote Originally Posted by demuro1 View Post
    because I don't know any better, this is really like my first attempt at a program all on my own.
    The rule is: start with the smallest possible scope. From local, to module, to global. Whichever suits your purpose best is the one to use.
    Since you are obviously passing the numbers as arguments, local is the way to go.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Sep 2008
    Posts
    13
    Elysia-I know this may be beneath you explaining but, while I think I understand the idea of local module and global how am I supposed to make my program work if my variable don't work throughout the entire program(global? right) I am using the same variables in all of the program so how could I make this work without a global variable?

    tabstop-I don't care what they store as. I want the values printed to show 2 decimal places. Will man printf give what I need to figure this out?

    Thanks you guys are all pretty awesome. I know some of these questions must seem really mundane but I'm pretty much doing this on my own so you guys are much appreciated

  12. #12
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,751
    It may be beneath Elysia explaining but I can tell you how local variables work.

    C allows you to declare local variables at the beginning of a compound statement (this includes functions and so forth). If you pass a local variable to a function, a copy of the value will be created for the function's use. This ensures that a variable is only valid as long as the item is being used.

    Imagine that div is used like this.

    a = div(u, v);

    And that div is declared like this.

    float div ( float u, float v );

    After using copies of u and v in div, the function returns the quotient as the return value. And as tabstop was saying, if you want precision to the hundredths place than you should use a floating point type like float or double.
    Last edited by whiteflags; 09-22-2008 at 04:30 PM.

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    And yes, man printf (or whatever reference you have to hand) will tell you how to print to a given precision (key word italicized for your pleasure).

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,904
    Quote Originally Posted by demuro1 View Post
    Elysia-I know this may be beneath you explaining but, while I think I understand the idea of local module and global how am I supposed to make my program work if my variable don't work throughout the entire program(global? right) I am using the same variables in all of the program so how could I make this work without a global variable?
    There are obviously 3 things in a programming language about scope.
    First is local. These variables will only live through the function and should be used to store specific data that only applies to the function, so it can work as it should. No other function or part of the program should be able to access these variables.

    Module scope is variables that are available to an entire source file. The advantages of this is that a lot of functions can share information. The disadvantage is that you may not know what function changes it or what the current state of it is inside another function.

    Global scope is that the entire program can see and use the variable. This enhances the disadvantages named above.

    So how do we get around these disadvantages, then? The best solution is to make as many variables as possible local. We can do this by letting functions take arguments and return arguments. These arguments are local but can pass information between two functions.
    So, say one function gets input. You pass the proper arguments for the function to store the data inside.
    Then you pass that input to the next function, and then the next, etc. They will all be local then (but beware of pointers), but you get to pass information around your program as necessary.

    As for the variables. They do not actually work differently depending on what format specified (ie %d) you use. Actually it's more of the thing that C is dumb. It does not know what type you're passing to functions, so you must explicitly tell printf what type of arguments you're passing. If you specify the wrong type, then printf will give you wrong output because you lied to it. It expects to treat the types in a different manner, and processing information in a wrong way just doesn't work out as you want. This also applies to reality, doesn't it?
    If you don't want to explicitly specify the type you're passing, then you're looking at the wrong language. You'll have to use a higher level. But if you want to stay close to the hardware (ie C), and still have more power/ability/flexibility, then you can try C++.
    That's the way it is.
    Last edited by Elysia; 09-23-2008 at 05:48 AM.

  15. #15
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,751
    Quote Originally Posted by Elysia View Post
    So, say one function gets input. You pass the proper arguments for the function to store the data inside.
    Then you pass that input to the next function, and then the next, etc. They will all be local then (but beware of pointers), but you get to pass information around your program as necessary.
    There is no reason to "beware of pointers;" they are not treated differently than any other variable if we are discussing implications of local scope. Copies of pointers are generated if they are arguments to functions, too.

    As for the variables. They do not actually work differently depending on what format specified (ie %d) you use. Actually it's more of the thing that C is dumb. It does not know what type you're passing to functions, so you must explicitly tell printf what type of arguments you're passing. If you specify the wrong type, then printf will give you wrong output because you lied to it.
    Absolutely C knows the types of variables passed to functions because that information is available from the parameter list. The only contexts in which it isn't available include variadic functions (such as printf) and macro functions. Just wanted to clear that up, since this piece of advice is more about printf than it is about C or variables in general.

    Furthermore, printf does work differently depending on the format: consider the differences between %o and %x, which print a number in octal and hexadecimal respectively.

    OP, if you're still reading this, printf's help file will contain everything you ever wanted to know about using printf, including printing to the hundredths place and so forth.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 04:45 AM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 10:42 PM
  3. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 01:05 PM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 12:58 PM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21