为什么我不能从两个ints返回一个double被划分 [英] Why can't I return a double from two ints being divided

查看:171
本文介绍了为什么我不能从两个ints返回一个double被划分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相对较新的编码,并有一个关于基本划分的问题。如何来到以下不返回答案我认为它会:

Relatively new to coding and have an issue regarding basic division. How come to following doesn't return the answer I thought it would:

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

我会把钱放在2.3333的结果上,但它只返回2.如果A和B然后重新分配到双倍的答案确实转向2.333。但是肯定是因为C已经是双重的了,它应该工作了吗?

I would have put money on the result being 2.3333, however it only returns 2. If A and B are then reassigned to being doubles the answer does turn to 2.333. But surely because C is already a double it should have worked?

int / int = double不起作用?

How come int/int=double doesn't work? Maybe an odd question but it's puzzled me.

推荐答案

这是因为您使用的整数除法版本 operator / ,它需要2 int s并返回 int 。为了使用 double 版本,它返回 double ,至少有一个 int 必须显式地转换为 double

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;

这篇关于为什么我不能从两个ints返回一个double被划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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