这题哪错了

来源:百度知道 编辑:UC知道 时间:2024/09/22 12:26:41
public class c1_1
{
public static void main(String[]args)
{
float x=9f,y;
if(x<1)
y=x;
else if(1<=x<10)
y=3*x-2;
else if(x>=10)
y=4*x;
}
System.out.println("y="+y);
}
public class c1_1
{
public static void main(String[]args)
{
float y=0,x=9;
if(x<1)
y=x;
else if(x>=1&&x<10)
y=3*x-2;
else if(x>=10)
y=4*x;
System.out.println("y="+y);
}
}
这是改正后的程序,可以正常运行了,但为什么一定要对Y赋予初始值?无论它的初始值是多少它最后的结果不都由是X决定的吗

public class c1_1
{
public static void main(String[]args)
{
float x=9f,y;
if(x<1)
y=x;
else if(1<=x<10) --- java不能使用数学中的表达式,改成if(1<=x && x<10)
y=3*x-2;
else if(x>=10)
y=4*x;
}
System.out.println("y="+y); -- 这句话要放到main()方法中,那么你的y要初始化,要不也会提示出错

----修改后
public class C1_1 {
public static void main(String[]args)
{
float x=9f,y = 0; //初始化了y
if(x<1)
y=x;
else if(1<=x && x<10) //x大于等于1,并且小于10
y=3*x-2;
else if(x>=10)
y=4*x;
System.out.println("y="+ y );
}

}
}

public class c1_1
{
public static void main(String[]args)
{
float x=9f,y = 0f;
if(x<1)
y=x;
else if(1<=x&&x<10)
y=3*x-2;
else if(x>=10)
y=4*x;
System.out.println("y="+y);
}

}

首先是else if(1<=x<10) 这个判断方式