Thread: divide long by double

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    58

    divide long by double

    HI,i was trying to do the following.I tried but cant figure out my error.I want the output to be 123.456
    Code:
    #include <stdio.h>
    
    int main(void){
    
    	unsigned int a=123456;
    	double b=a/1000;
    	
    	printf("&#37;d",b); //123.456 output wanted
    }

    Do help..

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by rahulsk1947 View Post
    HI,i was trying to do the following.I tried but cant figure out my error.I want the output to be 123.456
    Code:
    #include <stdio.h>
    
    int main(void){
    
    	unsigned int a=123456;
    	double b=a/1000;
    	
    	printf("&#37;d",b); //123.456 output wanted
    }

    Do help..
    Two mistakes:
    1. dividing two integers gives an integer answer. You want a floating point answer, so you need to make sure at least one of the numbers is floating point e.g. 1000.0
    2. %d is the wrong format specifier for a double. Read your documentation again to find the correct specifier.
    Last edited by iMalc; 10-30-2007 at 11:49 PM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    2. &#37;d is the wrong format specifier for a double. Read your documentation again to find the correct specifier.
    It's %f, not %lf, which you might expect.

    Also consider returning 0.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Testing some code, lots of errors...
    By Sparrowhawk in forum C Programming
    Replies: 48
    Last Post: 12-15-2008, 04:09 AM
  2. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  3. Dev-cpp - compiler options
    By tretton in forum C Programming
    Replies: 7
    Last Post: 01-06-2006, 06:20 PM
  4. Quick, Partiotion, and Insertion Sort
    By silicon in forum C++ Programming
    Replies: 0
    Last Post: 05-18-2005, 08:47 PM
  5. Replies: 15
    Last Post: 04-16-2003, 08:06 PM