import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
//your code here
Scanner sc =new Scanner(System.in);
int N=sc.nextInt();
int[] arr=new int[N];
for(int i=0;i<N;i )
arr[i]=sc.nextInt();
Solution s=new Solution();
s.Answer(arr,N);
}
}
class Solution
{
public void Answer(int [] arr,int N)
{
int p=0,ne=0,z=0,i=0;
while(i<arr.length)
{
if(arr[i]>0)
p ;
else if(arr[i]<0)
ne ;
else z ;
i ;
}
System.out.printf("%1.4f \n", p/N);
System.out.printf("%1.4f \n", ne /N);
System.out.printf("%1.4f\n ", z / N);
}
}
我已經為問題撰寫了上面的代碼給定一個大小為 N 個整數的整數陣列,任務是找到陣列中正數、負數和零的比率,最多小數點后四位。
例子:
輸入: a[] = {2, -1, 5, 6, 0, -3}
輸出: 0.5000 0.3333 0.1667
有 3 個正數、2 個負數和 1 個零。它們的比率為正:3/6 = 0.5000,負:2/6 = 0.3333,零:1/6 = 0.1667。
我編譯了上面的代碼,但它顯示了一個非法格式例外。但我不明白為什么它會這樣顯示。
我檢查了我在這段代碼中使用的所有語法。但我找不到那個問題。
請幫助我解決這個正負問題。
uj5u.com熱心網友回復:
package ddd;
import java.util.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
//your code here
Scanner sc =new Scanner(System.in);
int N= sc.nextInt();
int[] arr=new int[N];
for(int i=0;i<N;i )
arr[i]=sc.nextInt();
Solution s=new Solution();
s.Answer(arr,N);
}
}
class Solution
{
public void Answer(int [] arr,int N)
{
int p=0,ne=0,z=0,i=0;
while(i<arr.length)
{
if(arr[i]>0)
p ;
else if(arr[i]<0)
ne ;
else z ;
i ;
}
System.out.printf("%1.4f \n", p/(float)N);
System.out.printf("%1.4f \n", ne/(float)N);
System.out.printf("%1.4f\n ", z/(float)N);
}
}
我認為只需將 N 轉換為 float 即可解決您的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/531994.html
標籤:爪哇
