为什么浮点运算会在C#PointF中返回整数?

问题描述

我有以下语句使用所有平面数据类型。

ScaledCordinates.Bottomright = new PointF(((float)ScaleBottomright.X * (float)Scale),((float)ScaleBottomright.Y * (float)Scale));

分配给"ScaleBottomright.X" is 2.36523485"ScaleBottomright.Y" is 2.38020468的值。 "Scale" = 66.80098

我不明白为什么"ScaledCordinates.Bottomright"在我的应用中给我{X = 158 Y = 159}。 为什么float操作返回整数值?有时甚至令人沮丧的是输出是整数,有时是浮点数。我在double和float之间进行了各种转换,但结果相同。解决这些问题的最佳方法是什么?输出应为“浮动”数据类型。

解决方法

    public void sendGetRequest(String url){

        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        builder.connectTimeout(30,TimeUnit.SECONDS);
        builder.readTimeout(30,TimeUnit.SECONDS);
        builder.writeTimeout(30,TimeUnit.SECONDS);

        httpClient = builder.build();

        Request request = new Request.Builder().url(url).build();

        try (Response response = httpClient.newCall(request).execute()) {
            String responseBody = response.body().string();
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String perfectJSON = gson.toJson(JsonParser.parseString(responseBody));

            JSONObject json = new JSONObject(perfectJSON);

            JSONObject business = json.getJSONObject("business_profile");
            String phone = business.getString("support_phone");
            String id = json.getString("id");

            this.displayAlert(id+" > "+phone,perfectJSON);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

2.36523485 * 66.80098 = 158.000005910153

它们的小数部分都太小而无法满足浮点精度,根据the docs约为6-9位数。尽管相乘的结果仍然是2.38020468 * 66.80098 = 159.0000052245864 (即float):

System.Single
,

我假定无论类型ScaledCordinates.BottomRight是什么,(字段的)XY属性都是类型int

例如,它可能是类型Point,其X和Y是int s:X docsY docs

您可以将其更改为其他类型。但是只要它们是int,就无法保留浮点信息。