Type conversion

This is a discussion on Type conversion within the C Programming forums, part of the General Programming Boards category; I was just wondering if maybe the following isn't over complicating Code: #include <stdio.h> main() { int value1 = 12, ...

  1. #1
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751

    Type conversion

    I was just wondering if maybe the following isn't over complicating
    Code:
    #include <stdio.h>
    
    	main()
    	{
    		int  value1 = 12, value2 = 5;
    		float answer = 0;
    
    		answer = value1 / value2;
    		printf("The value of %d divided by %d is %f\n",value1,value2,answer );
    	}
    
    
    	Sample program output
    	The value of 12 divided by 5 is 2.000000
    The answer isn't correct and you have to assign the value 1 and 2 to a float type before getting your answer
    Code:
    answer = (float)value1 / (float)value2;
    would it not save time to just declare the values as type float in the first place?
    Code:
    /* type conversion */
    
    #include <stdio.h>
    
    int main()
    
    {
    
    float value1 = 12.0, value2= 5.0;
    float answer = value1 / value2;
    
    printf("The value of %.2f divided by %.2f is %.2f\n", value1, value2, answer);
    
    getchar();
    
    return 0;
    
    }
    I did this and it compiled fine without any errors. Is this bad form or an alternative?

  2. #2
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    your last code is the correct code. floats need to have .0 value for them to be recognized as a float and thus having a decimal

  3. #3
    Registered User kryptkat's Avatar
    Join Date
    Dec 2002
    Posts
    638

    Smile float div

    i would float val1 and val2 then float ans. the second is correct. also you need to make sure you use decimal points ie 1.0 when assigning anything float. interesting you can add two ints and get int but when you div you need float

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question on l-values.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 10-13-2005, 04:33 PM
  2. type conversion
    By peterx in forum C Programming
    Replies: 3
    Last Post: 10-08-2005, 04:03 PM
  3. ras.h errors
    By Trent_Easton in forum Windows Programming
    Replies: 8
    Last Post: 07-15-2005, 10:52 PM
  4. Windows using Dev-C++
    By Renegade in forum C++ Programming
    Replies: 15
    Last Post: 07-07-2005, 08:29 PM
  5. overloaded operator for type conversion error
    By mangoMan in forum C++ Programming
    Replies: 1
    Last Post: 03-10-2004, 07:38 PM

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