本文目錄一覽:
JAVA怎麼計算百分比?
int num1 = 7;
int num2 = 9;
// 創建一個數值格式化對象
NumberFormat numberFormat = NumberFormat.getInstance();
// 設置精確到小數點後2位
public String getPercent(int x,int total){
String result=””;//接受百分比的值
double x_double=x*1.0;
double tempresult=x/total;
numberFormat.setMaximumFractionDigits(2);
String result = numberFormat.format((float) num1 / (float) num2 * 100);
System.out.println(“num1和num2的百分比為:” + result + “%”);
比較運算符
比較運算符屬於二元運算符,用於程序中的變量之間,變量和自變量之間以及其他類型的信息之間的比較。比較運算符的運算結果是boolean型。當運算符對應的關係成立時,運算的結果為true,否則為false。比較運算符共有6個,通常作為判斷的依據用於條件語句中。
Java解釋器在沒有生成任何對象的情況下,以main作為入口來執行程序。每個類中可以定義多個方法,但main方法只能有一個。關鍵字public表示訪問權限,指明所有的類都可以使用這一方法。
以上內容參考:百度百科-Java
java百分比的輸入輸出
你要確定你需要輸幾個數字?
可以定義一個數組接受
然後再去計算
ListInteger arr = new ArrayListInteger();
Scanner s = new Scanner(Sysyem.in);
int a = s.nextInt;//如果輸入別的你自己判斷
if(a 0){
System.out.println(“你輸入的數字小於0,請重新輸入”);
}
arr.add(a);
int sum = 0 ;
for(int i= 0; iarr.size();i++ ){
sum += list.get(i);
}
for(int i= 0; iarr.size();i++ ){
System.out.println(list.get(i) + “的百分比是:” + list.get(i)/sum );
}
沒有測試 有錯在提問吧
java計算百分比的代碼怎麼寫?
public String getPercent(int x,int total){
String result=””;//接受百分比的值
double x_double=x*1.0;
double tempresult=x/total;
//NumberFormat nf = NumberFormat.getPercentInstance(); 注釋掉的也是一種方法
//nf.setMinimumFractionDigits( 2 ); 保留到小數點後幾位
DecimalFormat df1 = new DecimalFormat(“0.00%”); //##.00% 百分比格式,後面不足2位的用0補齊
//result=nf.format(tempresult);
result= df1.format(tempresult);
return result;
}
====================
idehub提供雲端手機、平板、pc瀏覽器等方式的java編程平台,讓你隨時隨地可以編寫java代碼,並有大神在線解答所有技術問題!關注code4a微信公眾號!
原創文章,作者:BOHN,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/131967.html