为什么在分配给 double 时除以两个 int 不会产生正确的值? [英] Why does dividing two int not yield the right value when assigned to double?

查看:32
本文介绍了为什么在分配给 double 时除以两个 int 不会产生正确的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

怎么会出现在下面的代码片段中

How come that in the following snippet

int a = 7;
int b = 3;
double c = 0;
c = a / b;

c 最终得到的值为 2,而不是人们所期望的 2.3333.如果 ab 是双精度型,则答案会变为 2.333.但肯定是因为 c 已经是一个 double 它应该可以处理整数吗?

c ends up having the value 2, rather than 2.3333, as one would expect. If a and b are doubles, the answer does turn to 2.333. But surely because c already is a double it should have worked with integers?

那么为什么 int/int=double 不起作用?

So how come int/int=double doesn't work?

推荐答案

这是因为您使用的是 operator/ 的整数除法版本,需要 2 ints并返回一个 int.为了使用返回 doubledouble 版本,必须将至少一个 int 显式转换为 双重.

This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.

c = a/(double)b;

这篇关于为什么在分配给 double 时除以两个 int 不会产生正确的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆