Hello,
I was trying to write a program that gives sum,product... of two integers, but, when i take ratio of two integers, it always gives "0" if number1 is less than number2.
Why is that?
Hello,
I was trying to write a program that gives sum,product... of two integers, but, when i take ratio of two integers, it always gives "0" if number1 is less than number2.
Why is that?
> when i take ratio of two integers, it always gives "0" if number1 is less than number2.
Without even looking at your code, I'm going to suggest that you have integer division which results in zero when the denominator is larger than the numerator.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
But i have made division variable in float. Even division is float, can't it have decimals when dividing two integers?
You misunderstood how the compiler seems the expression. In a nutshell, it goes like this:
(int)/(int) = (int), then the result gets converted into float.
You will have to convert at least one of the operands into float during the division, not after.
Devoted my life to programming...
Try adding a cast like this to your code:
Code:#include <stdio.h> #include <math.h> int main (void) { int n1; int n2; int sum; int diff; int pro; float quot; printf("Enter two integers as you like\n"); scanf("%d %d", &n1, &n2); sum = n1+n2; diff = abs(n1-n2); pro = n1*n2 ; quot = (float)(n1)/(float)(n2) ; printf("Sum of them is \n%d \n",sum); printf("Difference of them is \n%d \n",diff); printf("Product of them is \n%d \n",pro); printf("Quotient of them is \n%.2f \n",quot); return 0 ; }
Thank you both a lot. I got the idea now.