Why does dividing two int not yield the right value when assigned to double?(为什么将两个 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 时不会产生正确的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么将两个 int 分配给 double 时不会产生正确的值?
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
