+ 4
float Discount = 15 / 100 * 50; Yields zero cause all operands involved are integers, thus integer division takes place. float Discount = 15 / 100.0 * 50; This will do floating point calculation because 100.0 is a floating point literal.
25th Mar 2022, 11:39 AM
Ipang
+ 4
There are two types of division done by the '/' operator. Integer division and floating point division . Integer division does the division without any points, thus ends up with a remainder. But returns you only the quotient. Here, 15/100 has the quotient 0 and remainder 15. So you get 0*50=0. The second type of division done by the '/' operator is floating point division, and that's what you want here. It does division until the remainder is 0(or very close to 0) and thus can produce 7.5 as the answer in your question. When one of the numbers that you pass to the '/' operator is a float or double, it's gonna call the floating point version of the operator. Since your both operands are integers here, it's calling the internet division version. So as @Ipang said, you should pass one floating point number to the operator like the below: 15/100.0*50 or 15.0/100*50
25th Mar 2022, 12:04 PM
Rishi
Rishi - avatar
+ 4
Manav Roy Operation happens from right side so 15 / 100 = 0 If you want 7.5 then cast with float (float) 15 / 100
25th Mar 2022, 2:35 PM
AĶ¢J
AĶ¢J - avatar
+ 2
Manav Roy don't know what AĶ¢J was meaning by that, but no it's wrong. It won't do anything like 100/15
29th Mar 2022, 12:08 PM
Rishi
Rishi - avatar
+ 2
Manav Roy I mean if we assign value 15 / 100 with float data type then it doesn't mean that 15 / 100 will give result in float. here 15 and 100 are integer value not float value (as assigned to float data type) So if you divide lower integer value to higher integer value then result will be always 0 But if you want in decimal then RHS value should be cast with float or atleast lower or higher value should be in decimal. float a = 15 / 100; LHS = RHS LHS = float RHS != float means (15 && 100 are Integer so result would be integer)
29th Mar 2022, 12:18 PM
AĶ¢J
AĶ¢J - avatar