gpt4 book ai didi

java - 容易 for 循环不起作用

转载 作者:行者123 更新时间:2023-12-02 07:22:07 27 4
gpt4 key购买 nike

所以我试图让(例如)输入一些值:1 -2 -3 2 5正数的数量是 5 负数的数量是 -3总计为 3 平均值为 0.6我想让它像这样,但是当我运行它时,它不起作用哪一部分是错误的???

import java.util.*;


public class Welcome {

public static void main(String [] args){

Scanner input = new Scanner(System.in);
System.out.print("Enter an int value, the program exits if the input is 0: ");
int num = input.nextInt();
int countpos = 0;
int countneg = 0;
int totalnum = 0;
int total = 0;
double avg = 0.0;

while(num != 0){

if(num < 0)
countpos++;
else
countneg++;

total = total + num;
totalnum++;
}

System.out.print("num of pos is: " + countpos);
System.out.print("num of neg is: " + countneg);
System.out.print("total is: " + total);
System.out.print("the avg is: " + total / totalnum );

}

}

最佳答案

你也必须在循环中执行num = input.nextInt();

 while(num != 0){

if(num < 0)
countpos++;
else
countneg++;

total = total + num;
totalnum++;

num = input.nextInt();
}

关于java - 容易 for 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com