作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
新手问题:
void main () {
int A = 1;
int B = 2;
double C = A / B;
stdout.printf("C value is: %g\n", C);
}
这会打印:“C 值为:0”
void main () {
int A = 1;
double B = 2;
double C = A / B;
stdout.printf("C value is: %g\n", C);
}
这会打印:“C 值为:0.5”
我不明白为什么两种情况下结果都不是 0.5。
最佳答案
除法运算是对两个整数进行的,所以结果是一个整数。之后将其分配给 double 这一事实不会改变这一点。
你在你的问题中所做的,隐式转换是显式的,是
int A = 1;
int B = 2;
double C = (double) (A / B);
但是,如果您想使用 double 执行除法运算,您必须明确地将至少一个操作数转换为 double :
int A = 1;
int B = 2;
double C = ((double) A) / B;
有关算术运算的规则,请参阅 arithmetic expressions section of the Vala Manaual .相关位:
If both operands are of integer types, then the result will be the quotient only of the calculation (equivalent to the precise answer rounded down to an integer value.) If either operand is of a floating point type, then the result will be as precise as possible within the boundaries of the result type (which is worked out from the basic arithmetic type rules.)
关于vala:两个整数的商总是一个整数。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305625/
我是一名优秀的程序员,十分优秀!