• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

Java整型与浮点数据类型的转换

 

class java3_2
{
    public static void main(String[] args)
    {
        int a=155,b=9;
        float g,h;
        System.out.println("a="+a+",b="+b);
        g=a/b;
        System.out.println("a/b="+g+"\n");
        System.out.println("a="+a+",b="+b);
        h=(float)a/b;
        System.out.println("a/b="+h);
        System.out.println("(int)h="+(int)h);

    }

}

 

a/b=17.0

当两个整数相除时,小数点之后的数字会被截断,使得运算的结果保持为整数。

以下三种写法都可以使运算结果为浮点数:

(float)a/b

a/(float)b

(float)a/(float)b

要使结果为浮点数,就必须将两个整数种的一个或者二个强制转换为浮点数类型。

posted on 2022-04-12 20:03  王陈锋  阅读(458)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3