Home

Forums

Web development

 

 

 

 
     
 
dna88 Web development and Technology Forum
 
Profile   Register   Memberlist   Usergroups   FAQ   Search  Log in
A simple problem

 
Post new topic   Reply to topic    dna88 Forum Index -> Programming in Java, C, C#, VB, .NET Discussion Forum
Author Message
Moni
Beginner User
Beginner User


Joined: 19 May 2004
Posts: 32

Post Post subject: A simple problem Reply with quote

Code:

#include <stdio.h>
#include <conio.h>

int main (void)
{
     float s;
     s=1/2;
     printf("s= %f",s);
     getche();
     return 0;
}


When I run the above program why do I get s = 0.0000 ? Shouldn't it show 0.5 ? I noticed that I only get the expected 0.5 in the result if I use another variable like this :

Code:

float s,r=1;
s=r/2;   /* isn't it same as s=1/2 ? */


Why can't I divide 1/2 directly ? Why does it work when I use a variable (assigning a value of 1) ?
Fri Nov 26, 04 7:20 am
Back to top
Moni View user's profile Send private message
illusionist
Beginner User
Beginner User


Joined: 15 Jul 2004
Posts: 25

Post Post subject: Reply with quote

When you do something like this s = 1/2 what happens? After the division of 1 by 2(which are assigned to some others variables), the result is put into some temporary variables.Then the value of temporary variable is assigned to 's'.So the value of 's' depends on the value of temporary variable.

Now what should be the data type (int,float etc.) of the temporary variable depends on what your operands(1 and 2 here) are.If one of the operands was double type temporary variable would be double type,if one of the operands was float type temporary variable would be float type,if one of the operands was integer type temporary variable would be integer type,so on.Since at the time of s = 1/2; both the operands are integer the temporary variable becomes integer type. And hence temporary variable contains integer part of the result of 1/2 which is 0.At the time of s= r/2 (where r is float type) one of the operands is float type,so temporary variable is float type and it contains float version of the result 1/2,which is 0.5. Thats why it works this time.But you may also use 'casting' to avoid this type of confusion.
Fri Nov 26, 04 9:16 am
Back to top
illusionist View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    dna88 Forum Index -> Programming in Java, C, C#, VB, .NET Discussion Forum All times are GMT - 7 Hours
Page 1 of 1

 

Partners and Resources

Bangladesh hosting company

Bangladesh web design

Driven by phpBB © phpBB Group