我怎么能在最终结果中不记录 0

他们是

我正在做一个方法练习是关于输入一些大于 -50000 且小于 50000 的值,当用户输入 0 时,程序停止并计算一些结果。我的问题是当我输入所有正数并输入 0 退出时,程序将保存 0 数字并在我的最终结果中显示我最小的数字,这意味着当我输入 1,2,3,4,0 时最小的数字应该是 1 而不是 0,因为 0 是退出程序。我想我知道问题出在 for 循环中,最小的是保存输入值,但我只是不知道如何解决此问题以分隔输入编号和退出编号。

package exercise;
import java.util.Scanner;

public class array {
    static final Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
    
    
    System.out.println("Input some numbers , press 0 to exit");
    check();
    
}
    
    public static void check() {
        int pos=0;
        int neg=0;
        double topos=0;
        double toneg=0;
        double lar=0;
        double sma=0;
        double in;
        
        do {
            in = input.nextDouble();
            
            if(in>0 && in <50000) {
                pos++;
                topos=topos+in;
                
            }else if(in <0 && in>-50000) {
                neg++;
                toneg+=in;
            }
            for(double i=0;i<pos+neg;i++) {
                if(in>lar) {
                    lar=in;
                }
                if(in<sma &&in !=0) {
                    sma=in;
                }
                
            }
            }while(in !=0);
        
            
            System.out.println(neg+pos+" numbers input");
            System.out.println("Total pos "+topos);
            System.out.println("Total neg "+toneg);
            System.out.println("Aver pos "+topos/pos);
            System.out.println("Ave neg "+toneg/neg);
            System.out.println("Ave all "+(topos+toneg)/(pos+neg));
            System.out.println("Largest number "+lar);
            System.out.println("Smallest number "+sma);
                        
    }
        
}
杰托·马丁内斯

正如@sinclair 在评论中指出的那样,您sma以 0进行初始化,因此唯一可以替换sma值的数字是负数。要修复它,请sma以您的程序应识别的最大值进行初始化这样,sma如果需要,每个不是 0 的数字都将在比较和 repalce的值中正确使用

更改sma=0;sma=50000;

我使用 50000 作为您检查的最大值是 49999,如果这是用户输入的唯一数字,那么它是最小的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章