b
的输出,从阅读代码预期输出为0
而不是1
。
任何人都可以解释如何达到这个输出?
int a=5, b=6, c=1;
double x=0.5, y=1.0, z=1.5;
c = fcn1(a, b);
y = fcn2(y, a);
b = fcn3(x, y);
z = fcn3(c, b);
System.out.println("a="+a+", b="+b+", c="+c);
System.out.println("x="+x+", y="+y+", z="+z);
}
static int fcn1(int i, int j){
int k = i-j;
return (++k);
}
static double fcn2(double t, int n){
return (t*n);
}
static int fcn3(double u, double v){
return fcn1((int)(u*v), 2);
}
static double fcn3(int r, int s){
return fcn2(r,s);
答案 0 :(得分:0)
<强>输出强>:
a=5, b=1, c=0
x=0.5, y=5.0, z=0.0
<强>代码强>
import java.io.*;
import java.util.*;
public class Main
{
public static int fcn1(int i, int j){
int k = i-j;
return (++k);
}
public static double fcn2(double t, int n){
return (t*n);
}
public static int fcn3(double u, double v){
return fcn1((int)(u*v), 2);
}
public static double fcn3(int r, int s){
return fcn2(r,s);
}
public static void main(String[] args)
{
int a=5, b=6, c=1;
double x=0.5, y=1.0, z=1.5;
c = fcn1(a, b); //c=0
y = fcn2(y, a); //y=5.0
b = fcn3(x, y); //b=fcn1((int)2.5, 2) //b=1
z = fcn3(c, b); //z=c*b //z=0.0
System.out.println("a="+a+", b="+b+", c="+c);
System.out.println("x="+x+", y="+y+", z="+z);
}
}
答案 1 :(得分:0)
我会给你一个提示,你会自己理解它:
当您将double
投射到int
时,您将只获得自然部分,例如:
double d = 2.5;
int i = (int) d;
//i in this case equal to 2 and not 2.5
这种情况发生在这个方法中:
static int fcn3(double u, double v) {
return fcn1((int) (u * v), 2);//u = 0.5 v = 5.0 ## 0.5 * 5.0 = 2.5 ## (int) 2.5 = 2
//-----------------------------------^^------^^-----------------^^----------------^
}
此后的所有计算都很简单:
static int fcn1(int i, int j) {
int k = i - j; // i = 2 ## j = 2 ## 2 - 2 = 0
return (++k);//++0 = 1 <--------------------b
}