gpt4 book ai didi

java - 我如何获得正确的输出来打印数组中正数、负数和零数的分数?

转载 作者:行者123 更新时间:2023-12-02 03:20:10 26 4
gpt4 key购买 nike

public class Solution {
public static void main(String[] args) {
int ne = 0;
int p = 0;
int z = 0;
Scanner in = new Scanner(System.in);
int n = in .nextInt();
int arr[] = new int[n];
for (int arr_i = 0; arr_i < n; arr_i++) {
arr[arr_i] = in .nextInt();
}
for (int arr_i = 0; arr_i < n; arr_i++) {
if (arr[arr_i] > 0) {
p++;
} else if (arr[arr_i] < 0) {
ne++;
} else {
z++;
}
}
double n1 = p / n; // this is showing 0 ouput
double n2 = ne / n; // this is showing 0 ouput
double n3 = z / n; // this is showing 0 ouput
System.out.println(n1);
System.out.println(n2);
System.out.println(n3);
}
}

问题是打印正数、负数和零与数组中元素数量的分数。输出显示所有内容均为 0,请指出错误

最佳答案

使用下面的代码。您正在进行整数除法,将结果四舍五入为 0。

double n1=((double)p)/n;    
double n2=((double)ne)/n;
double n3=((double)z)/n;

关于java - 我如何获得正确的输出来打印数组中正数、负数和零数的分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733266/

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