为什么将两个 int 分配给 double 时不会产生正确的值?

编程入门 行业动态 更新时间:2024-10-21 23:00:38
本文介绍了为什么将两个 int 分配给 double 时不会产生正确的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

How come that in the following snippet

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

c 最终的值为 2,而不是预期的 2.3333.如果 a 和 b 是双精度数,那么答案确实会变成 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.为了使用返回 double 的 double 版本,必须将至少一个 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;

更多推荐

为什么将两个 int 分配给 double 时不会产生正确的值?

本文发布于:2023-07-29 08:55:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   两个   int   double

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!