+ 1

How come 13/3 is 4.0?

so i was doing this task where I was required to "think as a machine" and calculate an expression keeping in mind the priority of the operators. And this is the expression I got : 813%100/3+2.4. so here's what I did: 813%100=13. 13/3=4.33. 4.33+2.4=6.73. and I was wrong! so I tried to reproduce it in ide and realized that it calculated 13/3 as equal to 4.0! so my question is WHAT THE F?

31st Aug 2017, 9:02 PM
Edwin Myers
Edwin Myers - avatar
8 odpowiedzi
+ 3
/ Does not only display whole numbers, it returns the type that was divided. 13 / 3 is an int / int, so it returns an int. Since you likely assigned it's value to a double, the .0 was added. double a = 13/3; // equals 4.0 int b = 13/3; // equals 4 double c = 13.0 / 3; // equals 4.3333.. // since this is double / int int c = 13.0 / 3; // This is error
31st Aug 2017, 10:27 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
I don't write in Java, but I know that the % operator will only output the remainder of the dividend, and / will only display whole numbers. Try separating out the operations into variables for better flow and more control. Computers might be smart, but that's only because people made them smart. They're still just dumb rocks public class Program { public static void main(String[] args) { int abc = (int) 10; int def = (int) 3; int h = (int) abc/def; //division, output a whole number //10/3 = 3 1/3, output: 3 System.out.println(h); int g = (int) abc%def; //division, output the remainder of the dividend //10%3 = 3 1/3, output: 1 System.out.println(g); } }
31st Aug 2017, 9:26 PM
UPrejean
UPrejean - avatar
+ 2
It is dependent on the type. 13 and 3 are both whole numbers, so you'll get a whole number back. There's an easy hack though: 13/3 == 4 13/3. == 4.3333333333333 3 with a dot is short for 3.0, so now you're dividing a whole number by a float, and you'll get a float back.
31st Aug 2017, 9:48 PM
Schindlabua
Schindlabua - avatar
+ 2
double x = 13/3; will still give you a plain 4, if that is what you mean. On the right side you are juggling integers and doing integer operations, only afterwards it will be converted to double and stored in x.
31st Aug 2017, 9:53 PM
Schindlabua
Schindlabua - avatar
0
I didn't know that / will only display whole numbers hmm, I thought that was dependant on the type of the variable
31st Aug 2017, 9:28 PM
Edwin Myers
Edwin Myers - avatar
0
well I declared the type double since there was +2.4
31st Aug 2017, 9:50 PM
Edwin Myers
Edwin Myers - avatar
0
aww now I got it, thanks!
31st Aug 2017, 9:54 PM
Edwin Myers
Edwin Myers - avatar
0
thanks a lot!
31st Aug 2017, 10:48 PM
Edwin Myers
Edwin Myers - avatar