-3

I am writing simple program where I am doing operation like 1/3, 1/5 . But while printing o/p it prints 0.00 ..

int main()
{
 float res = 0.0;
 int no1 =1 ;
 int no2 = 3;

 res = (no1) / (no2) ;

 printf("Res:[%f] ",res);

 }

~

ideally it should print 0.3 but it prints 0.0000.

  • Because 1/3 on integer variables gives integer arithmetic, not float. There are thousands upon thousands of duplicates to this question, and your C book would tell you the answer as well. – Lundin Oct 28 '18 at 11:08
  • Integer division will result in an integer, you could make one of the operands a float `res = no1 / (float)no2;` – George Oct 28 '18 at 11:08
  • That's because you are dividing integers. If you use float for the numbers you'll get the expected result. – Will_Panda Oct 28 '18 at 11:08
  • You mention _one_ language in the title, but tagged it with two. You are either using C or C++ compilation - ask and tag the question in relation to just the one you are using, lest you get an answer that is specific to the one you are not using. – Clifford Oct 28 '18 at 11:22

1 Answers1

0

Because no1 and no2 have int type. It means that results of any operations also int. So 1/3 is 0 (int) and then 0 casts to float

Solution. Make no1 or no2 or both floating point. For example:

res = (float) no1 / no2;

or

float no1 = 1.0f;
  • Given that it is tagged both C and C++, an answer that would work in either might be more appropriate. The title specifis C, and this is C++. – Clifford Oct 28 '18 at 11:27