除法运算给我错误的结果 [英] Division operation is giving me the wrong result
问题描述
我正在尝试在Processing中将一个数除以另一个,而我一直得到错误的答案.
I'm trying to divide one number by another in Processing, and I keep getting the wrong answer.
float a;
a = 3/2;
println(a);
给我
1.0
那么答案应该是1.5.
when then answer should be 1.5.
尝试其他号码,
float a;
a = 2/3;
println(a);
给我
0.0
答案应该是0.666666 ....
when the answer should be 0.666666....
有什么我想念的吗?我查看了处理除法文档,看来我使用的语法正确.
Is there something I'm missing? I looked over the Processing documentation for division and it seems like I'm using the right syntax.
推荐答案
就像其他人说的那样,您正在使用整数除法.
Like others have said, you're using integer division.
请记住,int
值不能保留小数位.因此,如果您进行的计算会导致小数位,则这些值会被截断,并且只剩下整数部分(换句话说,就是整数部分) ).
Remember that int
values can't hold decimal places. So if you do a calculation that would result in decimal places, those values are truncated and you're left with only the whole number part (in other words, the integer part).
int x = 1;
int y = 2;
int z = x/y; //0
int x = 5;
int y = 2;
int z = x/y; //2
您使用的是 int文字值(如2
和3
这样的数字),并且它们没有小数位,因此Processing将它们视为int
值,并且它们遵守上述规则.
You're using int literal values (digits like 2
and 3
), and those don't have decimal places, so Processing treats them like int
values, and they obey the above rules.
如果您关心小数位,则可以将它们存储在float
或double
变量中:
If you care about the decimal places, then either store them in float
or double
variables:
float x = 1;
float y = 2;
float z = x/y; //.5
float x = 5;
float y = 2;
float z = x/y; //2.5
或者通过添加小数部分来使用float
文字:
Or just use float
literals by adding a decimal part:
float a = 2.0/3.0;
处理现在知道这些是float
值,因此您将保留小数位.
Processing now knows that these are float
values, so you'll keep the decimal places.
这篇关于除法运算给我错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!