Thread: Type casting

  1. #1
    Registered User
    Join Date
    Apr 2014
    Posts
    3

    Cool Type casting

    This code i made, utilizing the type casting construct, isn't outputting what i wanted. The output for 'Dollars' and 'Cents' are returning '0' for both. instead all i want it to do is seperate the two. for example changing the float value of amount to an integer, giving a dollar value. Thanks.

    Code:
    #include <stdio.h>
    int main()
    {
    double Amount;
    int Dollars, Cents;
    printf("Enter the Amount: ");
    scanf("%e", &Amount);
    Dollars = (int) Amount;
    Cents = (int) ((Amount - Dollars)*100);
    printf("%d\n", Dollars);
    printf("%d\n", Cents);
    return(0);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Your scanf format specification should be "%le" since you are reading into a double rather than a float. Also, note that due to floating point inaccuracy, merely casting the result to int might not give you what you want. If you can assume the particular format, then it might be simpler to just write:
    Code:
    if (scanf("%d.%d", &Dollars, &Cents) == 2)
    {
        printf("%d\n%d\n", Dollars, Cents);
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Advantages of c++ type casting over c type casting
    By kaibalya2008 in forum C++ Programming
    Replies: 10
    Last Post: 05-05-2009, 11:09 AM
  2. difference between type conversion and type casting
    By Bargi in forum C Programming
    Replies: 1
    Last Post: 01-23-2007, 03:17 AM
  3. Type casting
    By Lionmane in forum C Programming
    Replies: 28
    Last Post: 08-20-2005, 02:16 PM
  4. Type Casting
    By joshdick in forum C++ Programming
    Replies: 6
    Last Post: 09-06-2003, 08:30 PM
  5. type casting
    By henry in forum C++ Programming
    Replies: 1
    Last Post: 04-02-2003, 07:39 AM