+ 1

[Solved] Stupid question regarding division in Java

I'm trying to solve a code coach which involve division. To my surprise even if I declare the variable to float or double, unless I put f or d at the back 2/3 always gives 0.0. Is it necessary to put d/f at the back of the calculation expression? In other word, when should I put d / f at the back? https://code.sololearn.com/cltPK9gByb8c/?ref=app

18th Oct 2023, 7:48 AM
Wong Hei Ming
Wong Hei Ming - avatar
6 Antworten
+ 3
2 and 3, that is integer numbers, are always of type int. Division of two integers will always yield the quotient of an integer division (division with remainder). And that regardless of the target type! You add an f if you want the type to be float, you add d if you want the type to be double, you add L if you want the type to be long. And yes, you need to do that. But you can also use 2.0 or 3.0 which are literals of <double> type. And you can typecast, like 2/(double)3.
18th Oct 2023, 9:13 AM
Gordie
Gordie - avatar
+ 2
You get 0.0 because your target type is a floating point type. The division performed is integer, yielding an int zero. That int is then converted to the target type of float or double respectively.
18th Oct 2023, 9:39 AM
Gordie
Gordie - avatar
+ 1
Gordie, if as you said "division of two integers will always yield the quotient", shouldn't 2/3 yield 0? Why it gets 0.0?
18th Oct 2023, 9:33 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
Thanks. It is very different from Python. Need to remember cast or reassign to different data type... [EDITED] Tried to reassign double into int to the same variable, and it doesn't work.
18th Oct 2023, 9:50 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
You're welcome :) Yeah, all ints fit into a double type, no problem there. But not all doubles are integers, so you need to be explicit about that conversion.
18th Oct 2023, 10:04 AM
Gordie
Gordie - avatar
0
internal static string GetSolarName(string fileName, string solarId)        {            FileInfo file = new FileInfo(fileName);            using (ExcelPackage package = new ExcelPackage(file))            {                ExcelWorksheet worksheet = package.Workbook.Worksheets[0];                int rowCount = worksheet.Dimension.Rows;                for (int row = 1; row <= rowCount; row++)                {                    string id = worksheet.Cells[row, 1].Value?.ToString();                    string name = worksheet.Cells[row, 2].Value?.ToString();                    if (string.Equals(id, solarId, StringComparison.OrdinalIgnoreCase) ||                        string.Equals(name, solarId, StringComparison.OrdinalIgnoreCase))                    {                        return name;                    }                }            }            return "";        } كيف نحول هاذا الكود من ExcelPackage الى Stream بلغة C#
19th Oct 2023, 5:34 PM
Abdalaziz Tawfiq Yusr
Abdalaziz Tawfiq Yusr - avatar