简体   繁体   English

客观c浮动值

[英]objective c float values

Why we can not store the division result of two integers into the float variable ? 为什么我们不能将两个整数的除法结果存储到float变量中?

int a = 100;
int b =50;
float temp = b/a;

it gives t= 0 ! 它给出了t = 0!

also i did 我也做到了

int temp = b/a;

it gives t= 0 ! 它给出了t = 0!

but when I did 但是当我这样做的时候

float temp = (float)b / (float)a;

it gives proper result. 它给出了正确的结果。 Why so ? 为什么这样 ?

The reason why float temp = b/a; float temp = b/a;的原因float temp = b/a; gives 0 while float temp = (float)b/a; 给出0而float temp = (float)b/a; gives 0.5 is that the compiler determines the output type of the division operation based upon the types of the operands, not the destination storage type. 给出0.5是编译器根据操作数的类型而不是目标存储类型确定除法运算的输出类型。 Put simply: 简单地说:

int   /   int = int
float /   int = float
int   / float = float
float / float = float

So when you do float temp = b/a; 所以当你做float temp = b/a; you're doing in integer divide of b and a , and then storing the resulting integer (0 in your example) into a variable of type float . 你在ba整数除法中,然后将得到的整数(在你的例子中为0)存储到float类型的变量中。 In essence, by the time the value is converted to floating-point you have already lost the information you are looking for (assuming you wanted to do a floating-point divide), and the conversion is not going to bring it back. 本质上,当值转换为浮点时,您已经丢失了所需的信息(假设您想要进行浮点除法),并且转换不会将其恢复。

In order to get the result you want (again, assuming that you want to do a floating-point divide), you need to cast at least one of the operands to float before you divide. 为了得到你想要的结果(再次,假设你想要进行浮点除法),你需要除法之前将至少一个操作数强制转换为float

int a = 100;
int b =50;
float temp = (float)b/a;

Its integer division - 50/100 is 0, the remainder (can use modulus) is 50. 它的整数除法 - 50/100为0,余数(可以使用模数)为50。

You will need to use floats, whether you cast from int or start with them is up to you. 您将需要使用浮点数,无论您是从int转换还是从它们开始都取决于您。

The below statement means, you are casting your integer values into float before staring the operation 下面的语句表示,您在启动操作之前将整数值转换为float

float temp = (float)b / (float)a;

So could be seen as below 所以可以看作如下

float temp = (float)50 / (float)100;

then 然后

float temp = 50.0 / 100.0 ;

And result 结果

temp = 0.5;

In your case 50/100 is 0.2. 在你的情况下,50/100是0.2。 By obtaining the result for two integer numbers the result will also be in integer form so it truncates the decimal part giving you 0 alone. 通过获得两个整数的结果,结果也将是整数形式,因此它截断小数部分,仅给出0。 But in case of float it is considered as a floating division so you will get 0.2 但是在浮动的情况下,它被认为是一个浮动分区,所以你会得到0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM