当前位置: 首页 > 知识库问答 >
问题:

输入的不工作数字的基本最小值、最大值、平均值和总数

郎健柏
2023-03-14

我无法使此程序正确运行。我所有的答案,最小值,最大值,平均值都是零。我知道我在开始时将它们初始化为零,但它们应该在整个代码中都改变吗?

public static void main(String[] args) {
    // TODO Auto-generated method stub
int a,b;
int max;
double average;
int min;
int total;
max=0;
min=0;
total=0;
Scanner keyboardInput = new Scanner(System.in);
System.out.println(" Enter a number :");
a = keyboardInput.nextInt();
System.out.println(" You entered :"+ a);
if (a>=0)
{a=max;
max=min;}
total=a;
System.out.println(" Max and min are "+ max  +" & " + min + " The total and average is    :" +total + " & "+a);             
System.out.println(" Enter a second number");

b = keyboardInput.nextInt();

System.out.println(" You entered :"+ b);
if (b>=a)
{b=max;}
if  (b<=a)
{b=min;}

average= (a+b)/2;
total= a+b;
System.out.println(" Max and min are "+ max + " & " + min + " and the total & average     are :" +total + " & " +average +" respectively.");

//c = keyboardInput.nextDouble();


}

}

输出:输入数字:

2个

您输入:2

最大值和最小值为0

输入第二个数字

3.

您输入:3

最大值和最小值为0

共有3个答案

松铭
2023-03-14

而不是

 if (a>=0)
 {  max=a;
    max=min;  }

最大值应分配给a,最小值应分配给最大值和最小值。否则,它会将a设置为max,即0,然后将max设置为min,再次设置为0。

if (a>=0)
 {  max=a;
    min=max;  }

到处更新赋值问题。记住左变量被分配了右变量的值

韩刚洁
2023-03-14
public static void main(String[] args) {
    int a, b;
    int max;
    double average;
    int min;
    int total;
    max = 0;
    min = 0;
    total = 0;
    Scanner keyboardInput = new Scanner(System.in);
    System.out.println(" Enter a number :");
    a = keyboardInput.nextInt();
    System.out.println(" You entered :" + a);
    if (a >= 0) {
        //modify a=max;
        max = a;
        //modify max=min;
        min = max;
    }
    total = a;
    System.out.println(" Max and min are " + max + " & " + min
            + " The total and average is    :" + total + " & " + a);
    System.out.println(" Enter a second number");

    b = keyboardInput.nextInt();

    System.out.println(" You entered :" + b);
    if (b >= a) {
        //modify b=max;
        max = b ;
    }
    if (b <= a) {
        b = min;
    }
    // modify average= (a+b)/2;
    average = (double)(a + b) / 2;
    total = a + b;
    System.out.println(" Max and min are " + max + " & " + min
            + " and the total & average     are :" + total + " & "
            + average + " respectively.");

    // c = keyboardInput.nextDouble();

}
蒋栋
2023-03-14

因为你的任务颠倒了:

该行:

a=max;

应该是:

max=a;

max为零,您正在用max覆盖a,使a也为零。

您在b上也犯了同样的错误。

 类似资料: